Search code examples
mongodbmongoosemongodb-queryaggregation-frameworkpymongo

How to make one field merging multiple string field


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'},
]

Solution

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