根据ID Mongodb

时间:2018-10-30 09:43:16

标签: node.js mongodb mongoose

我想根据部门集合中的部门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}
    ]

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

预先感谢

1 个答案:

答案 0 :(得分:2)

您可以使用$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
}