对于集合的每个文档,它都有一个字符串数组。我如何计算所有这个集合中数组的每个元素的重复时间?现在我可以找到所有不同的元素,但是Map Reduce函数有点棘手,我还没有完全理解。
Doc A
{
_id:
name:
actors: ["a", "b", "c"]
}
Doc B
{
_id:
name:
actors: ["a", "d"]
}
Doc C
{
_id:
name:
actors: ["a", "c", "f"]
}
我想得到一个统计结果: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
}