mongodb-在嵌套数组中找到
我的目标是:
- 以
status = true
获取所有文档。 - 并仅在
life
数组中使用active = true
返回对象。
以下是我的mongoDB文档的样子:
{
"name": "justine",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : false
}
}
]
},
{
"name": "okumu",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : true
}
}
]
}
预期输出:
{
"name": "justine",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
}
}
]
},
{
"name": "okumu",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : true
}
}
]
}
这是我所做的:
await Users.find({ life: { $elemMatch: { status: true, life: { $elemMatch: { active: false } } } }});
这对于第一个条件很好,如果不满足第二个条件,则没有返回整个对象,但是,如果满足,即使是active = false
对象将返回。
如果您能帮助我,我将不胜感激,不是MongoDB专家。
My goal is to:
- Get all the documents with
status=true
. - And return only objects with
active=true
in thelife
array.
Below is what my MongoDB documents look like:
{
"name": "justine",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : false
}
}
]
},
{
"name": "okumu",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : true
}
}
]
}
Expected output:
{
"name": "justine",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
}
}
]
},
{
"name": "okumu",
"life" : [
{
"status" : true,
"service" : [
{
"partner" : "pat 1",
"active" : true,
},
{
"partner" : "pat 2",
"active" : true
}
}
]
}
This is what I did:
await Users.find({ life: { $elemMatch: { status: true, life: { $elemMatch: { active: false } } } }});
This is working well for the first condition, in case the second condition is not met, the entire object is not returned, however, if it's met, even the active=false
objects are returned.
I'll be grateful if you can help me out, am not a MongoDB expert.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为使用
.find()
查询很复杂(可能无法可行)。您应该使用
.aggregate()
查询。$ match
- 带有life.status
的过滤文档 true 。$ project
-2.1
$ filter
- 用状态
true 在life> life
array document。2.1.1
$ map
- 合并life
文档与结果 2.1.1.1 。。2.1.1.1
$ filter
- 内部$ filter
操作员用active> active
istrue true
服务
服务>服务
数组中的文档。示例mongo playground
I think it is complex (possible not doable) with the
.find()
query.You should use
.aggregate()
query.$match
- Filter document withlife.status
istrue
.$project
-2.1
$filter
- Filter the document withstatus
istrue
inlife
array document.2.1.1
$map
- Merge thelife
document with the Result 2.1.1.1.2.1.1.1
$filter
- The inner$filter
operator to filter the document withactive
istrue
forservice
document inservice
array.Sample Mongo Playground