Mongodb 查找条目';s文档中每个数组中数组元素的计数

Mongodb 查找条目';s文档中每个数组中数组元素的计数,mongodb,Mongodb,我收集了以下文件: [ {p: [1, 2, 3, 4]}, {p: [1, 2, 7, 9, 10]}, {p: [3, 5]} ] 我想知道所有文档中p的每个元素在其他文档的p中出现了多少次。正确的结果应该是使用以下元素进行收集: [ {pElement: 1, count: 2}, {pElement: 2, count: 2}, {pElement: 3, count: 2}, {pElement: 4, count: 1},

我收集了以下文件:

[
    {p: [1, 2, 3, 4]},
    {p: [1, 2, 7, 9, 10]},
    {p: [3, 5]}
]
我想知道所有文档中
p
的每个元素在其他文档的
p
中出现了多少次。正确的结果应该是使用以下元素进行收集:

[
    {pElement: 1, count: 2},
    {pElement: 2, count: 2},
    {pElement: 3, count: 2},
    {pElement: 4, count: 1},
    {pElement: 7, count: 1},
    {pElement: 9, count: 1},
    {pElement: 10, count: 1},
    {pElement: 5, count: 1}
]
如何实现这一点?

您应该在以下阶段使用:

  • 分解
    p
    数组,并为每个元素生成一个文档。您可以使用运算符来执行此操作
  • 根据
    p
    值对生成的文档进行分组,并使用运算符和累加器运算符统计每个文档的出现次数
  • 使用运算符将前一阶段结果重新整形为
    {pElement:p,count:c}
  • 并使用运算符根据
    计数
    值对它们进行排序
  • 最终的聚合代码如下所示:

    db.collectionName.aggregate([ 
                { $unwind: "$p" }, 
                { $group: { _id: "$p", count: { $sum: 1 } } }, 
                { $project: { _id: 0, pElement: "$_id", count: 1 } }, 
                { $sort: { count: -1 } }
    ])
    
    结果将是:

    { "count" : 2, "pElement" : 3 }
    { "count" : 2, "pElement" : 2 }
    { "count" : 2, "pElement" : 1 }
    { "count" : 1, "pElement" : 5 }
    { "count" : 1, "pElement" : 10 }
    { "count" : 1, "pElement" : 9 }
    { "count" : 1, "pElement" : 7 }
    { "count" : 1, "pElement" : 4 }