【问题标题】:mongoDb find number of entries in a document and distinct entries by fieldmongoDb 查找文档中的条目数和按字段区分的条目
【发布时间】:2015-10-10 14:21:25
【问题描述】:

我的文档结构是:

[{
    "l": {
    "ln": "Hyderabad",

    },
    "cid": "customer1",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Hyderabad",

    },
    "cid": "customer2",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Delhi",

    },
    "cid": "customer3",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Delhi",

    },
    "cid": "customer3",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer1",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer5",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer6",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer6",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}]

我的 o/p 应该是:

[{
    "ln": "Hyderabad",
    "entries": 2,
    "numberofdistinctcustomers": 2,
    "customers": [
    "customer1",
    "customer2"
    ]
} {
    "ln": "Delhi",
    "entries": 2,
    "numberofdistinctcustomers": 1,
    "customers": [
    "customer3"
    ]
} {
    "ln": "Bangalore",
    "entries": 4,
    "numberofdistinctcustomers": 3,
    "customers": [
    "customer1",
    "customer5",
    "customer6"
    ]
}]

有人可以帮我吗?我知道为此我们需要使用 $group by ln 来查找 entries。如何找到不同cids 的数量?

请帮我解决这个问题?

【问题讨论】:

    标签: mongodb mongoose mongoid mongodb-query


    【解决方案1】:

    您应该使用aggregation 来获得预期的输出。

    首先您需要按l.ln 分组,然后使用$addToSet 获得不同的customers。要获得numberofdistinctcustomers,您可以在投影中使用$size 运算符。

    查询将如下所示:

    db.collection.aggregate({
        $group: {
        _id: "$l.ln",
        "entries": {
            $sum: 1
        },
        "dis": {
            $addToSet: "$cid"
        }
        }
    }, {
        $project: {
        "ln": "$_id",
        "entries": 1,
        "customers": "$dis",
        "numberofdistinctcustomers": {
            "$size": "$dis"
        }
        }
    })
    

    【讨论】:

    • @user1920 你遇到了什么错误?在实现上述查询时,您可能会遗漏一些东西。
    • 我收到以下错误:Error("Printing Stack Trace")@:0 ()@src/mongo/shell/utils.js:37 ([object Object],[object Object] )@src/mongo/shell/collection.js:866 @(shell):17 未捕获的异常:聚合失败:{“errmsg”:“异常:无效的运算符'$size'”,“代码”:15999,“确定” : 0 } 如果我删除 "numberofdistinctcustomers": { "$size": "$dis" } 它工作正常@Vishwas
    猜你喜欢
    • 2017-06-14
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多