Home > OS >  Merging arrays into one array in same field MongoDB
Merging arrays into one array in same field MongoDB

Time:06-15

I have a question on merging arrays into one array in same field, but they are in different objects. I hope you will understand what I wanted after looking at the code below.

 db.addresses.find().pretty()
{
        "_id" : ObjectId("62a72be40c7db0af0b79d721"),
        "rollingStockNumber" : "922698325786980137200129101715063039706000000",
        "addresses" : [
                "Raximova",
                "Raximova",
                "Raximova",
                "Nazarbek",
                "Oxunboboyeva",
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("62a8727978c18925711d40f2"),
        "rollingStockNumber" : "922698012567076507200129101700057022060000000",
        "addresses" : [
                "Toshkent",
                "Chuqursoy",
                "Chuqursoy",
                "Chuqursoy",
                "Chuqursoy",
                "Chuqursoy",
                "Chuqursoy",
                "Toshkent",
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("62a878d778c18925711d40f7"),
        "rollingStockNumber" : "922720020326980977200102111555058048630000000",
        "addresses" : [
                "Oxangaron",
                "Oxangaron",
                "Oxangaron",
                "Oxangaron",
                "Oxangaron",
                "Oxangaron",
                "Jaloir"
        ],
        "__v" : 0
}

I wanted to merge "addresses" arrays in one array called "allAddresses", used $group, $concat, but failed...

 "allAddresses" : [
                    "Raximova",
                    "Raximova",
                    "Raximova",
                    "Nazarbek",
                    "Oxunboboyeva",
                    "Toshkent",
                    "Chuqursoy",
                    "Chuqursoy",
                    "Chuqursoy",
                    "Chuqursoy",
                    "Chuqursoy",
                    "Chuqursoy",
                    "Toshkent",
                    "Oxangaron",
                    "Oxangaron",
                    "Oxangaron",
                    "Oxangaron",
                    "Oxangaron",
                    "Oxangaron",
                    "Jaloir"
            ]

How can I achieve that? Thanks in advance.

CodePudding user response:

  1. $group - Group by null and add addresses into addresses array. It returns a nested array.

  2. $project - With $reduce to flatten nested array.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      addresses: {
        $push: "$addresses"
      }
    }
  },
  {
    $project: {
      allAddresses: {
        $reduce: {
          input: "$addresses",
          initialValue: [],
          in: {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

  • Related