[英]How to get an Array in Nodejs from a nested document in Mongodb through Mongoose?
[英]How to filter and get required data from a nested document in MongoDB?
我的数据库中有这个结构。
[
{
_id: ObjectId("6386ef039775398be3620c76"),
firstName: 'A',
lastName: 'BA',
age: 34,
history: [
{ disease: 'fever', cured: true },
{ disease: 'malaria', cured: false }
]
},
{
_id: ObjectId("6386ef239775398be3620c77"),
firstName: 'AA',
lastName: 'BA',
age: 24,
history: [
{ disease: 'cold', cured: true },
{ disease: 'thyroid', cured: false }
]
}
]
我想要实现的是一个查询,它会给我这样的数据:
询问
db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
预期结果:
[
{
_id: ObjectId("6386ef039775398be3620c76"),
firstName: 'A',
lastName: 'BA',
age: 34,
history: [
{ disease: 'malaria', cured: false }
]
},
{
_id: ObjectId("6386ef239775398be3620c77"),
firstName: 'AA',
lastName: 'BA',
age: 24,
history: [
{ disease: 'thyroid', cured: false }
]
}
]
我试过的是
1.
db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
db.collection.aggregate([
{
$project: {
history: {
$filter: {
input: "$history",
as: "items",
cond: { cured: false }
},
},
},
},
]);
db.collection.find({history:{$elemMatch:{cured:true}}},{'history.cured':1})
但是这些查询都没有给出预期的结果,
疑问/问题:
任何帮助将非常感激。 如果这个问题太基础了,我深表歉意。
一种选择是将您的查询尝试合并到:
cured
: false 项的文档$filter
history
数组只包含这些项目db.collection.aggregate([
{$match: {
history: {$elemMatch: {cured: false}}
}},
{$set: {
history: {
$filter: {
input: "$history",
cond: {$eq: ["$$this.cured", false]}
}
}
}}
])
在playground 示例中查看它是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.