MongoDB:使用MapReduce计算数组元素的重复时间

标签 mongodb spring-data-mongodb mongodb-java

假设集合中的每个文档都有一个字符串数组。我如何计算所有这个集合中数组每个元素的重复时间?现在我可以找到所有不同的元素,但是 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/

相关文章:

spring - Spring-MongoDb聚合框架中如何使用$cond操作

node.js - 我可以将整个 MongoDB 集合缓存在内存中以提高查询性能吗?

node.js - NodeJS 注册 - 用户名区分大小写(唯一字段)

python - 如何将 MongoDB 中的 JSON 插入的created_at字段转换为Python中的日期时间对象

spring - spring-data-mongodb/k8s “Database name must not contain slashes, dots, spaces, quotes, or dollar signs”

java - 是否可以在 spring-data-mongodb 中注入(inject)自定义 Jackson ObjectMapper?

mongodb - 我应该如何构建 MongoDB 的数据模式?

java - com.mongodb.DB.authenticate(String,String) 是在内存中进行身份验证还是调用 mongo db?

MongoDB java-driver插入日期

java - MongoDB+Azure+Android : Error: com. mongodb.MongoException:不与master对话并且重试用完