Mohamd Ali
Mohamd Ali

Reputation: 2245

MongoDB merge int arrays in one result

I have this aggregation result

[
  {
    "ids": [1,100]
  },
  {
    "ids": [200, 100, 3]
  }
]

I want to merge them as one result like this:

[
    1,
    200,
    100,
    3
]

I have tried group but the result not like I want:

{
    $group: {
        _id: 1,
        merged: {
            $push: "$ids"
        }
    }
}

result:
[
  {
    "_id": 1,
    "merged": [
      [1, 100],
      [200, 100, 3]
    ]
  }
]

Upvotes: 0

Views: 81

Answers (1)

Takis
Takis

Reputation: 8705

Query

  • we dont have $concat accumulator
  • you can do it with $unwind , $group $addToSet
    (null or 1 its the same, as long each member is grouped with same key, null is more common)
  • or you could do it with $push and $reduce $union
  • here is the first approach looks easier

PlayMongo

aggregate(
[{"$unwind": {"path": "$ids"}},
  {"$group": {"_id": null, "ids": {"$addToSet": "$ids"}}},
  {"$unset": ["_id"]}])

Upvotes: 1

Related Questions