Igor Couto
Igor Couto

Reputation: 33

Merge two documents in the same collection in MongoDB

I've been tryng to merge some duplicate documents in my collection called Cities.

Consider the following:

{
    "_id": 1,
    "Name": "Santa Monica",
    "State": "California"
},
{
    "_id": {"$oid":"5ec5fcc993ce00388429278a"},
    "Name": "Santa Monica",
    "State": "California",
    "TimeZone": "UTC−8",
    "Population": 90401,
    "State": "California"
}

The second entry does have more information, like TimeZone and Population. I want to merge both in only one object, preserving the first _id like this:

{
    "_id": 1
    "Name": "Santa Monica",
    "State": "California",
    "TimeZone": "UTC−8",
    "Population": 90401,
    "State": "California"
}

I know that I have to use aggregations but don't know how. The documentation lacks a clear example of how to do that at the same collection.

Thanks in advance.

Upvotes: 2

Views: 238

Answers (1)

Valijon
Valijon

Reputation: 13103

You need to group documents by Name and State fields and merge them.

Try this one:

db.Cities.aggregate([
  {
    $group: {
      _id: {
        "Name": "$Name",
        "State": "$State"
      },
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    "$replaceWith": {
      "$mergeObjects": {
        "$reverseArray": "$data"
      }
    }
  }
])

MongoPlayground

Note: $reverseArray allows flip grouped array

Upvotes: 2

Related Questions