I have the following query:
cursor=self.postCol.aggregate([
{ \"$graphLookup\" : {
\"from\": \"pCol\",
\"startWith\": \"$parent\",
You can replace the else condition with below using $let
operator.
{
$let: {
vars: {
obj: {
"$arrayElemAt": ["$parents", 0]
}
},
in: "$$obj.pValue"
}
}
You can use the $switch operator and the $let operator to $project
your field.
The $let
variable operator let you assign a value to a variable which can be used in the "in" expression as shown in my other answer here.
With the $switch
operator, we can perform very clean case-statement.
db.postCol.aggregate([
{ "$graphLookup": {
"from": "postCol",
"startWith": "$parent",
"connectFromField": "parent",
"connectToField": "_id",
"as" : "parents"
}},
{ "$project": {
"pValue": {
"$switch": {
"branches": [
{ "case": { "$gt": [ { "$size": "$pValue"}, 0 ] },
"then": "$pValue" }
],
"default": {
"$let": {
"vars": { "p": { "$arrayElemAt": [ "$parents", 0 ] }},
"in": "$$p.pValue"
}
}
}
}
}}
])