I have a schema that is similar to this.
{id: Number,
line_items: [{
id: String,
quantity: Number,
revi
You can find this another way without $map
and $unwind
used $redact like this :
db.collectionName.aggregate({
"$match": {
"line_items.review_request_sent": {
"$exists": true
}
}
}, {
"$redact": {
"$cond": {
"if": {
"$eq": [{
"$ifNull": ["$review_request_sent", "null"]
}, "null"]
},
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}
}, {
"$match": {
"line_items": {
"$size": 1
}
}
}).pretty()
In above query first match
check whether review_request_sent
is presents or not in redact
$ifNull use to check whether review_request_sent
presents or not if not then it replaced to "null"
and $eq
to check "null"
this will return documents like
{ "_id" : ObjectId("55e6ca322c33bb07ff2c163e"), "id" : 1, "line_items" : [ ] }
{ "_id" : ObjectId("55e6ca322c33bb07ff2c163f"), "id" : 2, "line_items" : [ { "id" : 39 } ] }
{ "_id" : ObjectId("55e6ca322c33bb07ff2c1640"), "id" : 3, "line_items" : [ ] }
and after that last match check only those documents whose line_items
array contains value i.e $size to 1