MongoDB query to try multiple cases using aggregate, $group, $switch…returning error Unrecognized pipeline stage name: ‘$switch’
Using MongoDB aggregate to see if a first field and/or a second field have value(s), and if so, to increment the NumberMatches
by either 1 or 2 (depending on whether one or both exampleA
and exampleB
have values), and to increment MatchesTotal
by the values of exampleA/exampleB. I am using Mongo’s $switch, as with this example from Stack Overflow, and $group.
However, I am getting the error message Unrecognized pipeline stage name: '$switch'
. Right now the $switch
is outside of $group
. Previously I had tried using the $switch
within MongoDB $group
to try the query, but got another error message unknown group operator '$switch'
. How can I use $switch and $group together in order to do this incrementation/sum ternary query in MongoDB?
$switch query with $group inside:
db.examples.aggregate([
{
"$match": {
$or : [
{
$and : [
{"exampleField.exampleA": {$type: 16}},
{"exampleField.exampleB": { $type: 16 }}
]
},
{
"exampleField.exampleA": {$type: 16}
},
{
"exampleField.exampleB": {$type: 16}
}
]
}
},
{
$switch: {
"branches": [
{ "case":
{ "$eq": [ "$exampleField.exampleA", null ] },
"then": {
$group: {
_id: null,
NumberMatches: { $sum: 1 },
MatchesTotal: { $sum: "exampleField.exampleB" }
}
}
},
{ "case": {
"$eq": [ "exampleField.exampleB", null ] },
"then": {
$group: {
_id: null,
NumberMatches: { $sum: 1 },
MatchesTotal: { $sum: "$exampleField.exampleA" }
}
}
}
],
"default": {
$group: {
_id: null,
NumberMatches: { $sum: 2 },
MatchesTotal: { $sum: "$exampleField.exampleA" + "exampleField.exampleB" }
}
}
}
},
]).forEach( function(myDoc) { print( myDoc) } );
Alternate $group query with $switch inside (also didn’t work):
$group: {
_id: null,
NumberMatches: {
$switch: {
"branches": [
{ "case": { "$eq": [ "$exampleField.exampleA", null ] }, "then": { $sum: 1 } },
{ "case": { "$eq": [ "exampleField.exampleB", null ] }, "then": { $sum: 1 } }
],
"default": { $sum: 2 }
}
},
MatchesTotal: { $sum: "$exampleField.exampleA" + "$exampleField.exampleB" }
}
Go to Source
Author: maudulus