MongoDB:用MapReduce统计数组元素的重复次数
MongoDB: count the repetitive time of array element with MapReduce
假设集合中的每个文档都有一个字符串数组。我怎么能计算所有这个集合中数组的每个元素的重复时间?现在我可以找到所有不同的元素,但是 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"]
}
我想得到一个统计结果 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
stage to output a document for each element in the actors
array and the $group
阶段按 actors
数组中的值对文档进行分组,然后
通过 $sum
运算符:
计算每个组的文档数(将数组元素作为一个组出现)
db.collection.aggregate([
{ "$unwind" : "$actors" },
{ "$group": { "_id": "$actors", "count": { "$sum": 1} } }
])
操作 returns 以下结果与您的期望非常匹配,但不会为您提供 key/value 对的文档:
/* 0 */
{
"result" : [
{
"_id" : "f",
"count" : 1
},
{
"_id" : "d",
"count" : 1
},
{
"_id" : "c",
"count" : 2
},
{
"_id" : "b",
"count" : 1
},
{
"_id" : "a",
"count" : 3
}
],
"ok" : 1
}
假设集合中的每个文档都有一个字符串数组。我怎么能计算所有这个集合中数组的每个元素的重复时间?现在我可以找到所有不同的元素,但是 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"]
}
我想得到一个统计结果 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
stage to output a document for each element in the actors
array and the $group
阶段按 actors
数组中的值对文档进行分组,然后
通过 $sum
运算符:
db.collection.aggregate([
{ "$unwind" : "$actors" },
{ "$group": { "_id": "$actors", "count": { "$sum": 1} } }
])
操作 returns 以下结果与您的期望非常匹配,但不会为您提供 key/value 对的文档:
/* 0 */
{
"result" : [
{
"_id" : "f",
"count" : 1
},
{
"_id" : "d",
"count" : 1
},
{
"_id" : "c",
"count" : 2
},
{
"_id" : "b",
"count" : 1
},
{
"_id" : "a",
"count" : 3
}
],
"ok" : 1
}