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 }