sadsun
sadsun

Reputation: 11

How to convert array of documents to array in mongodb aggregation

I have a document similar to this:

{
  "field1": "a",
  "field2": {
    "subfield1": "sa",
    "subfield2": [
      {
        "name": "abc"
      },
      {
        "name": "def"
      }
    ]
  }
}

I want something like this:

{
   "field1":"a",
   "field2":{
      "subfield1":"sa",
      "subfield2":["abc","def"]
   }
}

Thanks in advance!

Upvotes: 1

Views: 816

Answers (1)

J.F.
J.F.

Reputation: 15187

Using projection into find:

db.collection.find({/*your find query*/},
{
  "field1": 1,
  "field2.subfield1": 1,
  "field2.subfield2": "$field2.subfield2.name"
})

Example here

Using aggregate:

db.collection.aggregate([
  {
    "$project": {
      "field1": 1,
      "field2.subfield1": 1,
      "field2.subfield2": "$field2.subfield2.name"
    }
  }
])

Example here

Also you can add "_id": 0, to not output the _id. Examples here and here

Upvotes: 2

Related Questions