gpt4 book ai didi

node.js - Mongodb根据id获取数组中其他集合数据的个数

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:56 27 4
gpt4 key购买 nike

我想根据部门集合中的部门 ID 获取 list 计数

我的收藏看起来像这样:

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 的 list 计数

这是我想要的回复:

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

在 Mongoose 中最好的方法是什么?

提前致谢

最佳答案

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

关于node.js - Mongodb根据id获取数组中其他集合数据的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53061379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com