In my database, I have the following data structure.
[
{
_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 }
]
}
]
I am trying to create a query that will retrieve data like this:
Query
db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
Expected Result:
[
{
_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 }
]
}
]
Here are the queries I have tried:
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})
However, none of these queries are producing the desired result.
Doubts/ Questions:
- Is it possible to directly obtain the expected result from a query?
- Where did my queries go wrong?
- Which resources should I refer to for more advanced concepts related to this query?
Any assistance would be greatly appreciated. Apologies if this question seems too elementary.