Dominique Altrez
Dominique Altrez

Reputation: 123

How to Merge Array and Document Field in Mongo DB

I have this document in MongoDB

[
    {
        "locations": [5, 5],
        "id": "fff"
    },
    {
        "locations": [7, 7],
        "id": "aaa"
    },
    {
        "locations": [9, 9],
        "id": "ccc"
    }
]

And I want to merge the array field and string field into a field that contains a combination of them like this

{
    "device": [
        ["fff", 5, 5],
        ["aaa", 7, 7],
        ["ccc", 9, 9]
    ]
}

Is it possible to do this with aggregation? Thank you.

Upvotes: 1

Views: 174

Answers (1)

Ashh
Ashh

Reputation: 46441

You can use $concatArrays to merge two fields and then $group to make it two dimensional array

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "devices": { "$push": { "$concatArrays": [["$id"], "$locations"] } }
  }}
])

Output

[
  {
    "devices": [
      ["fff", 5, 5],
      ["aaa", 7, 7],
      ["ccc", 9, 9]
    ]
  }
]

Upvotes: 1

Related Questions