假设集合中的每个文档都有一个字符串数组。我如何计算所有这个集合中数组每个元素的重复时间?现在我可以找到所有不同的元素,但是 MapReduce 函数有点棘手,我还没有完全理解。
Doc A
{
_id:
name:
actors: ["a", "b", "c"]
}
Doc B
{
_id:
name:
actors: ["a", "d"]
}
Doc C
{
_id:
name:
actors: ["a", "c", "f"]
}
我想得到a:3 b:1 c:2 d:1 f:1的统计结果。
最佳答案
您可以采取的另一种路线是aggregation framework 。以上面的集合为例
填充测试集合:
db.collection.insert([
{ "_id" : 1, "name" : "ABC1", "actors": ["a", "b", "c"] },
{ "_id" : 2, "name" : "ABC2", "actors" : ["a", "d"] },
{ "_id" : 3, "name" : "XYZ1", "actors" : ["a", "c", "f"] }
])
使用 MongoDB 3.4.4 或更高版本:
db.collection.aggregate([
{ "$unwind" : "$actors" },
{ "$group": { "_id": "$actors", "count": { "$sum": 1} } },
{ "$group": {
"_id": null,
"counts": {
"$push": {
"k": "$_id",
"v": "$count"
}
}
} },
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$counts" }
} }
])
输出
{
a: 3,
b: 1,
c: 2,
d: 1,
f: 1
}
使用 MongoDB 3.2 及更低版本:
以下聚合管道操作使用 $unwind
阶段,为 actors
数组和 $group
中的每个元素输出文档。 阶段根据 actors
数组中的值对文档进行分组,然后
通过 $sum
计算每个组的文档数量(给出数组元素作为一个组的出现次数) 运算符:
db.collection.aggregate([
{ "$unwind" : "$actors" },
{ "$group": { "_id": "$actors", "count": { "$sum": 1} } }
])
该操作返回以下结果,这与您的期望非常匹配,但不会为您提供键/值对形式的文档:
/* 0 */
{
"result" : [
{
"_id" : "f",
"count" : 1
},
{
"_id" : "d",
"count" : 1
},
{
"_id" : "c",
"count" : 2
},
{
"_id" : "b",
"count" : 1
},
{
"_id" : "a",
"count" : 3
}
],
"ok" : 1
}
关于MongoDB:使用MapReduce计算数组元素的重复时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953765/