I have three queries and now I want to change this to MongoDB aggregation and below is the code:
db.mycollection.count({$and:[$requestB:{$exists:false},[$requestC:{$exists:false}]}) db.mycollection.count({requestB:{$exists:true}}) db.mycollection.count({requestC:{$exists:true}})
Now i want to change this code to aggregation but it did not work
db.mycollection.aggregate( [ { $group: { '_id' : { user_id: '$user_id'}, requestA_count: { $sum: { $cond: [ {$and: [{$eq: ["$requestB", null]}, {$eq: ["requestC", null]}}}, 1, 0 ] } }, requestB_count: { $sum: { $cond: [ {requestB:{'$exists':true}}, 1, 0 ] } }, requestC_count: { $sum: { $cond: [ {requestC:{'$exists':true}}, 1, 0 ] } }, } }, { $project: { _id: 0, user_id: '$_id.user_id', requestA_count: 1, requestB_count: 1, requestC_count: 1 } } ] );
Asked
Active
Viewed 35 times
1

turivishal
- 34,368
- 7
- 36
- 59

Jay Park
- 308
- 1
- 6
- 14
1 Answers
0
You can use $type
instead of $exists
inside $group
,
db.collection.aggregate([
{
$group: {
"_id": { user_id: "$user_id" },
requestA_count: {
$sum: {
$cond: [
{
$and: [
{ $ne: [{$type: "$requestA"}, "missing"] },
{ $eq: [{$type: "$requestB"}, "missing"] },
{ $eq: [{$type: "$requestC"}, "missing"] }
]
}, // you need to close bracket here not below
1, 0
]
}
},
requestB_count: {
$sum: { $cond: [{ $ne: [{ $type: "$requestB" }, "missing"] }, 1, 0] }
},
requestC_count: {
$sum: { $cond: [{ $ne: [ { $type: "$requestC" }, "missing" ] }, 1, 0] }
}
}
},
{
$project: {
_id: 0,
user_id: "$_id.user_id",
requestA_count: 1,
requestB_count: 1,
requestC_count: 1
}
}
])

turivishal
- 34,368
- 7
- 36
- 59
-
thanks, form your link, why requestA_count total number is 0? { "requestA": 1, "user_id": 1 }, This object does not contain requestB and requestC so requestA_count should be 1 not 0 – Jay Park Sep 10 '20 at 05:31
-
requestA_count counts all the document which do not have the field requestB and requestC – Jay Park Sep 10 '20 at 05:32
-
My idea is to find the total number of requestB filed exist in the document, requestC exist in the document. requestA is to find and count the object do not contain requestB and requestC – Jay Park Sep 10 '20 at 05:38
-
ok check now its corrected, my intention is to give a way how you can do, that the logical changes you can change it right? – turivishal Sep 10 '20 at 05:41