【发布时间】:2023-03-20 02:15:01
【问题描述】:
我正在尝试查询集合中包含特定用户数据的所有文档而不返回所有子文档(有大量子文档)
示例文档
[
{
"id": 1,
"title": "Document 1",
"users": [
{ "id": "a", "name": "User 1" },
{ "id": "b", "name": "User 1" },
]
},
{
"id": 2,
"title": "Document 2",
"users": [
{ "id": "b", "name": "User 1" },
]
},
{
"id": 3,
"title": "Document 3",
"users": [
{ "id": "a", "name": "User 1" },
{ "id": "b", "name": "User 1" },
{ "id": "c", "name": "User 1" },
]
}
]
这里我们有 3 个文档,其中 2 个使用了 id A,来查询我正在做的用户 A 存在的所有文档:
collection.findManyByQuery({
users: {
$elemMatch: {
id: 'a'
}
}
})
这会返回正确的 id 为 1 和 3 的文档。但是我试图返回用户数组中只有用户 A 对象的文档,所以我的结果看起来像这样
[
{
"id": 1,
"title": "Document 1",
"users": [
{ "id": "a", "name": "User 1" },
]
},
{
"id": 3,
"title": "Document 3",
"users": [
{ "id": "a", "name": "User 1" },
]
}
]
我尝试了$unwind: 'users' 和几个过滤器,但没有得到想要的结果。
【问题讨论】:
标签: mongodb mongoose subdocument