简体   繁体   English

MongoDB 聚合计数

[英]MongoDB aggregation count

I have collections Users and Numbers.我有用户和数字集合。 Each number has AllocatedToUserId (ObjectId) field, User can have many numbers.每个号码都有 AllocatedToUserId (ObjectId) 字段,用户可以有多个号码。 How can I in single query return User with NumbersCount?如何在单个查询中使用 NumbersCount 返回用户? I wrote this我写了这个

db.getCollection('Users').aggregate([
      {'$lookup': {from: "Numbers",
                   localField: "_id",
                   foreignField: "AllocatedToUserId",
                   as: "Numbers"}
      },{ '$project' : {_id:0,
                       document: '$$ROOT',
                       count: {$size:'$Numbers'}}}
      ])

But with this code I got structure of response like that:但是通过这段代码,我得到了这样的响应结构:

[{document, count},{document, count},{document, count}...]

Where each document has Numbers collection, and I'd like to have count inside document and without collection of numbers.每个document都有Numbers集合,我想在document内部进行count并且没有数字集合。 Is it possible?是否可以? Thanks!谢谢!

You don't necessarily need to project another field with the $$ROOT system variable, just project the fields from the users schema.您不一定需要使用$$ROOT系统变量投影另一个字段,只需投影用户架构中的字段。 The following example assumes you have a user with the schema:以下示例假设您有一个具有架构的用户:

Exmple Users Schema示例用户架构

{
    "_id": ObjectId
    "firstName": String,
    "lastName": String,
    "age": Integer,
    "location": String
}

Pipeline管道

db.getCollection('Users').aggregate([
    {
        "$lookup": {
            "from": "Numbers",
            "localField": "_id",
            "foreignField": "AllocatedToUserId",
            "as": "Numbers"
        }
    },
    {   
        "$project": {
            "firstName": 1,
            "lastName": 1,
            "age": 1,
            "location": 1,
            "Numbers": 0,
            "count": { "$size": "$Numbers" } 
        }
    }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM