Reputation: 9809
We need to push/addtoset only if the key in the document ne []
How do we achieve this
{
"_id" : ObjectId("xxxxxx"),
"shop" : "REQ4",
"bolt" : "5647",
"nut" : "1111",
}
{
"_id" : ObjectId("xxxxxx"),
"shop" : "REQ4",
"bolt" : "2314",
"nut":[]
}
Aggregates.group("$shop", Accumulators.addToSet("bolt", "$bolt"),Accumulators.addToSet("nut", "nut"))//only if nut ne []
Expected output:
{ "_id" : "REQ4", "bolt" : ["5647", "2314"], "nut" : ["1111"]
Upvotes: 0
Views: 132
Reputation: 46451
You can first $push
then can use $filter
to ruled out []
db.collection.aggregate([
{ "$group": {
"_id": "$shop",
"bolt": { "$push": "$bolt" },
"nut": { "$push": "$nut" }
}},
{ "$addFields": {
"nut": {
"$filter": {
"input": "$nut",
"cond": { "$ne": ["$$this", []] }
}
}
}}
])
Upvotes: 1