I use mongoTemplate to query my mongodb database, and I want to do some counting in my collections. I want to group by id and include counting with conditions. I used this query in mongoshell
db.scenarios.aggregate([
{ $match: { bid: "build_1481711758" } },
{
$group: {
_id: "$bid",
nb: { $sum: 1 },
nbS: {
"$sum": {
"$cond": [
{ "$eq": ["$scst", true ] },
1, 0
]
}
},
nbE: {
"$sum": {
"$cond": [
{ "$eq": ["$scst", false ] },
1, 0
]
}
}
}
}
])
and it returns what I want, but I dont know how to convert it to java mongotemplate.
Please help :)
You can simplify the pipeline to
since the
$cond
operator evaluates a boolean expression to return one of the two specified return expressions and thescst
field by default returns a boolean.If using the current Spring Data release which has support for the
$cond
operator via the$project
pipeline, then this can be converted to (untested):If your Spring Data version does not support this, a workaround is to implement the AggregationOperation interface to take in a
DBObject
:Then implement the
$group
operation as a DBObject in the aggregation pipeline that is the same as the one you have:which you can then use as:
For a more flexible and better performant approach which executes much faster than the above, consider running an alternative pipeline as follows