SeekingKnowledge
SeekingKnowledge

Reputation: 15

How to union/merge arrays of arrays in MongoDB using aggregations?

From this object:

{
  "_id": null,
  "reqs": [
    ["ab","ac","ab"],
    ["ac","cd"],
    ["ab","ae"]
  ]
}

How can I get this result using an aggregation:

{
  "_id": null,
  "reqs": ["ab","ac","cd","ae"]
}

Upvotes: 0

Views: 28

Answers (1)

R2D2
R2D2

Reputation: 10737

Here it is:

mongos> db.a.find()
{ "_id" : ObjectId("5ff7a8c0bfa9f0b53f4b395d"), "reqs" : [ [ "ab", "ac", "ad" ], [ "ad", "dc", "ab" ], [ "ac", "ad", "dc" ] ] }
mongos> db.a.aggregate([{  $unwind:"$reqs"}  , {$unwind:"$reqs" } , {$group:{_id:null , reqs:{$addToSet:"$reqs"}}}  ])
{ "_id" : null, "reqs" : [ "ac", "ad", "dc", "ab" ] }
mongos> 

Upvotes: 1

Related Questions