我在使用 Mongoose 时尝试查询深度嵌套的子文档时遇到了麻烦。 我的数据库结构是这样的:
{
"_id": "662aa6ccae109745e30dc664",
"username": "username",
"email": "[email protected]",
"lists": [
{
"_id": "662aa6dbae109745e30dc66a"
"name": "list",
"content": [
{
"_id": "662aa6eeae109745e30dc670"
"name": "product",
"quantity": 30,
"brands": [],
}
],
},
],
}
我想要的只是查询产品_id(“_id”:“662aa6eeae109745e30dc670”)并获取列表和用户_id(“_id”:“662aa6dbae109745e30dc66a”和“_id”:“662aa6ccae109745 e30dc664" 分别在此示例中)。
我尝试过查询:
const user = await findOne({ 'lists.content._id': '662aa6eeae109745e30dc670' })
但这会返回整个用户对象。我如何查询才能只返回产品对象(因为我可以使用“child.parent()”方法来获取 listId)
$unwind
每个数组lists
然后lists.content
。然后匹配 lists.content._id
的条件并投影您想要的字段。
db.collection.aggregate([
{ $unwind: "$lists" },
{ $unwind: "$lists.content" },
{
$match: {
"lists.content._id": "662aa6eeae109745e30dc670"
}
},
{
$project: {
// _id will be included anyway
list_id: "$lists._id",
content_id: "$lists.content._id"
}
},
// limit to just one doc if that's a requirement; NOT recommended
{ $limit: 1 }
])
结果:
[
{
"_id": "662aa6ccae109745e30dc664",
"content_id": "662aa6eeae109745e30dc670",
"list_id": "662aa6dbae109745e30dc66a"
}
]
如果您想要嵌套在原始文档中的
_id
字段,请使用此 $project
阶段:
{
$project: {
"lists._id": 1,
"lists.content._id": 1
}
}
结果:
[
{
"_id": "662aa6ccae109745e30dc664",
"lists": {
"_id": "662aa6dbae109745e30dc66a",
"content": {
"_id": "662aa6eeae109745e30dc670"
}
}
}
]