我的数据库中有这样的结构。
[
{
_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})
但是这些查询都没有给出所需的结果,
疑问/问题:
1.是否可以直接从查询中获得预期结果?
1.我的查询哪里出错了?
1.我应该阅读哪些材料来涵盖与此查询相关的更多高级概念?
任何帮助都将不胜感激。如果这个问题太简单,我很抱歉。
1条答案
按热度按时间omtl5h9j1#
一个选项是合并查询尝试以:
1.获取包含
cured
项的所有文档:假的$filter
history
数组以仅包含此类项目了解它在playground example上的工作原理