mongodb - Return array of elements from multiple arrays -
i got collection of companies looks this. want merge other documents deals. need this:
{ "_id" : objectid("561637942d25a7644cae993e"), "locations" : [ { "deals" : [ { "name" : "1", "_id" : objectid("561637942d25a7644cae9940") }, { "name" : "2", "_id" : objectid("562f868ce73962c626a16b15") } ] } ], "deals" : [ { "name" : "3", "_id" : objectid("562f86ebe73962c626a16b17") } ] } { "_id" : objectid("561637942d25a7644cae993e"), "locations" : [ { "deals" : [ { "name" : "4", "_id" : objectid("561637942d25a7644cae9940") } ] } ], "deals" : [] }
to this:
{ "deals": [{ "name" : "1", "_id" : objectid("561637942d25a7644cae9940") },{ "name" : "2", "_id" : objectid("562f868ce73962c626a16b15") },{ "name" : "3", "_id" : objectid("562f86ebe73962c626a16b17") },{ "name" : "4", "_id" : objectid("561637942d25a7644cae9949") }] }
but have failed this. seems if want deals grouped 1 array should not use unwind since create more documents because need group once. attempt not work @ all.
{ "$project": { "_id": 1, "locations": 1, "deals": 1 } }, { "$unwind": "$locations" }, { "$unwind": "$locations.deals" }, { "$unwind": "$deals" }, { "$group": { "_id": null, "deals": { "$addtoset": "$locations.deals", "$addtoset": "$deals" } } }
you should first use filter documents reduce size of documents process in pipeline using $match
operator. need $unwind
"locations" array after use $project
operator reshape documents. $cond
operator used return single element array [false]
if deals
field empty array or deals
value because $unwind
ing empty array throw exception. of course $setunion
operator return array of element appear in locations.deals
array or deals
array. use $setdifference
operator filter out false
element merged array. need $unwind
stage deconstruct deals
array. there can $group
documents.
db.collection.aggregate([ { "$match": { "locations.0": { "$exists": true } } }, { "$unwind": "$locations" }, { "$project": { "deals": { "$setdifference": [ { "$setunion": [ { "$cond": [ { "$eq" : [ { "$size": "$deals" }, 0 ] }, [false], "$deals" ]}, "$locations.deals" ]}, [false] ] } }}, { "$unwind": "$deals" }, { "$group": { "_id": null, "deals": { "$addtoset": "$deals" } }} ])
which returns:
{ "_id" : null, "deals" : [ { "name" : "1", "_id" : objectid("561637942d25a7644cae9940") }, { "name" : "2", "_id" : objectid("562f868ce73962c626a16b15") }, { "name" : "3", "_id" : objectid("562f86ebe73962c626a16b17") }, { "name" : "4", "_id" : objectid("561637942d25a7644cae9940") } ] }
Comments
Post a Comment