Search code examples
mongodbaggregation

Merge records if one field matches, but not if another field has values in both records MongoDb aggregation


I have some records like :

{
id: 1,
phone: "+15555555555",
name: "Acme CO.",
vendorcode: "ACMEC"
},
{
id: 2,
phone: "+15555555555",
name: "Acme corporation company",
vendorcode: "ACMECOMPANY"
},
{
id: 3,
phone: "+15555555555",
name: "Acme Incorporated",
vendorcode: null
}

I want to merge records:

IF phone field matches, merge the records. (can overwrite values with the values of the next record being merged).

But if there are vendorcode non-null values in multiple records, create an arrray of values. So "vendorcode" in the new record would be an array.

I would like the output of the above collection to be something like:

{
phone: "+15555555555",
name: "Acme Co.",
vendorcode: ["ACMEC","ACMECOMPANY"]
}

in a new collection.

How to write an aggregation for this in mongodb?


Solution

    • $group by phone, select first name, phone
    • $ifNull will return vendorcode if its not null
    • $addToSet to make array of unique vendorcode
    • $project to remove _id field
    • $out to write query result in new collection, this will create a new collection and write this query result
    db.collection.aggregate([
      {
        $group: {
          _id: "$phone",
          phone: { $first: "$phone" },
          name: { $first: "$name" },
          vendorcode: {
            $addToSet: { $ifNull: ["$vendorcode", "$$REMOVE"] }
          }
        }
      },
      { $project: { _id: 0 } },
      { $out: "newCollectionName" }
    ])
    

    Playground