1

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"] }

1 Answer 1

1

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" ] }
]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Anthony. Sorry, just need little more, how do I get unique values into array? Seems some of Ids have duplicate phone numbers in collection.
You can use $setUnion aggregation for that
@Nar If you need any help in that then please ask a new question i will help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.