'Why it's going in else part even there is value in document that satisfying the if condition?
I want to count total number of Documents with same value for details.iseligible.value, i.e if there is two 'Yes' for details.iseligible.value then count for 'YES' should be 2 and if there is three 'NO' for details.iseligible.value then count for 'NO' is 3 and if details.iseligible.value is not found in documents or it's value is 'NONE' then return 'NONE' and count total number of 'NONE', getting right value for most of mongodb documents but i don't know why this document not satisfying if condition and going to else part of condition.
Document
{
_id:"some_id",
details:[
{
degree:{
value:'ABC'
},
iseligible:{
value:'YES'
}
}
]
}
let query1={'details.degree.value': 'ABC' };
await User.aggregate([
{
$match:query1
},
{
$project:{
_id:'$_id',
result:{
$reduce:{
input: '$details',
initialValue: {},
in: {
$cond:{
if: { $eq: [ "$$this.degree.value",'ABC' ] },
then: {$ifNull: ['$$this.iseligible.value', 'NONE']},
else:''
}
}
}
}
}
},
{ $unwind: "$result" },
{ $sortByCount: "$result" }
])
Solution 1:[1]
Are you just wanting the count for found documents? Or do you also need the data from each matched document?
If you just need the count, you could do something like this:
db.collection.aggregate([
{
$match: {
"details.iseligible.value": "YES"
}
},
{
$count: "numDocsFound"
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Matt Oestreich |