Home > Net >  unwind array field in document while keeping first fields
unwind array field in document while keeping first fields

Time:08-24

here is the document I have.

[{ id:'786786', name: 'john', contacts:[{id:'1', text:'first contact'},{id:'1', text:'second contact'}]}]

Each array contains multiples contacts.

Do you know how to $unwind contacts array to geta document for each contact in contatcs :

[{name:'john', text:'first contact'},{name:'john', text:'second contact'}]

I tried $unwind and $map and it didn't worked

Thanks

I finally did it ! Thanks to Tom Slabbaert

CodePudding user response:

Just $unwind suffices here:

db.collection.aggregate([
  {
    "$unwind": "$contacts"
  },
  {
    $project: {
      name: "$name",
      text: "$contacts.text"
    }
  }
])

Mongo Playground

  • Related