Nar
Nar

Reputation: 75

Convert array of embedded documents into array of elements in mongoDB

What is the query or aggregation operator I can use to get this ?

Input:

{"_id": "id1", "contacts": [{"phone": "xxx", "email":"[email protected]"}, {"phone":"yyy"}, {"phone":"zzz", "email":"[email protected]"}] }
{"_id": "id2", "contacts": [{"phone": "aaa", "email":"[email protected]"}, {"phone":"bbb"}, {"phone":"ccc"}] }

Output:

(just need phone numbers, other contacts.fields can be dropped)

{"_id": "id1", "contacts": ["xxx", "yyy", "zzz"] }
{"_id": "id2", "contacts": ["aaa", "bbb", "ccc"] }

Upvotes: 1

Views: 84

Answers (1)

Ashh
Ashh

Reputation: 46441

Simply use $project aggregation pipeline stage.

db.collection.aggregate([
  {
    "$project": {
      "contacts": "$contacts.phone"
    }
  }
])

Output

[
  { "_id": "id1", "contacts": [ "xxx", "yyy", "zzz" ] },
  { "_id": "id2", "contacts": [ "aaa", "bbb", "ccc" ] }
]

Upvotes: 1

Related Questions