Home > Software engineering >  How to make one field merging multiple string field
How to make one field merging multiple string field

Time:12-11

I have one collection whose structure is like this:

[
{ u1: 'xx', u2: 'gg' },
{ u1: 'yy', u2: 'Nk' },
{ u1: 'zz', u2: 'hh' },
{ u1: 'ya', u2: 'hj' },
{ u1: 'ab', u2: 'jd' },
]

I want to make a field which should have result of both fields. for example:

[
    {user: 'xx'},
    {user: 'gg'},
    {user: 'yy'},
    {user: 'Nk'},
    {user: 'zz'},
    {user: 'hh'},
    {user: 'ya'},
    {user: 'hj'},
    {user: 'ab'},
    {user: 'jd'},
]

CodePudding user response:

See the playground: https://mongoplayground.net/p/C2PrY3UPVLs

Project each object into a list, then unwind.

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      user: [
        "$u1",
        "$u2"
      ]
    }
  },
  {
    $unwind: "$user"
  }
])
  • Related