0

I merge 2 collections into one

mother:

{
_id: ObjectId(),
address: "something"
}

child:

{
  _id: ObjectId(),
  name: "something",
  contacts: [{
    "phone": "+144543823..."
  }, {
    ...
  }]
}

Now I when I merge 2 collections into one:

{
  "lookup": {
    from: 'contacts',
    localField: 'address',
    foreignField: 'name',
    as: 'contacts'
  }
}

Now I have results similar to the below payload:

{
  _id: ...,
  address: ...,
  contacts: [{
    _id: ..,
    name: ...,
    contacts: [
      "phone": "+144543823..."
    ]
  }]
}

Now in my project I get the phones:

$project: {
   phones: "$contacts.contacts.phone"
}

The output is as follow:

phones: [["+144543823..."], ["+48....], ["..."]]
name: ...
....

How can I get a simple array of phones. Using unwind would make the result very big and then I need to groupBy if I'm not mistaken! Is there an efficient way to do this? If not how can I do it with unwind and not missing other fields like name, address,...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.