繁体   English   中英

根据id Mongodb从数组中获取其他收集数据的计数

[英]Get the count of other collection data from the array based on id Mongodb

我想根据部门集合中的部门ID获取清单的数量

我的收藏如下:

departments : [
{_id: 838383, name: Dump}
{_id: 838384, name: Recycle}
]
checklists: [
{_id: 33333, department_id:838383, name: Tyre},
{_id: 33334, department_id:838383, name: Car body},
{_id: 33335, department_id:838383, name: Wheel},
{_id: 33336, department_id:838383, name: Mirror}
]

现在我要获取部门列表,包括基于部门ID的清单数量

这是我想要的回复:

departments : [
    {_id: 838383, name: Dump, checklists_count: 4}
    {_id: 838384, name: Recycle, checklists_count: 0}
    ]

用猫鼬做这件事的最好方法是什么?

提前致谢

您可以使用$lookup实现此目的。

db.departments.aggregate(
 { "$lookup": {
       "from": "checklists",
       "localField": "_id",
       "foreignField": "department_id",
       "as": "checklists"
    }}
    ,
    {
        "$project":
        {_id:1,"name":1,
            checklists_count:{$size:"$checklists"}
        }
    })

结果:

{
    "_id" : 838383,
    "name" : "Dump",
    "checklists_count" : 4
},
{
    "_id" : 838384,
    "name" : "Recycle",
    "checklists_count" : 0
}

暂无
暂无

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

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