skip to Main Content

Scenario

Example Mongo DB documents
Doc 1
{
_id 123
Customer: customer A
State: TX
City: Houston
checksum: 1111
IsBundlled:
}

Doc 2
{
_id 1234
Customer: customer B
State: TX
City: Houston
checksum: 1111
IsBundlled:
}

Doc 3
{
_id 12345
Customer: customer c
State: NY
City: Buffalo
checksum: 2222
IsBundlled:

}

Checksum field is populated in app code using State and City fields.

Problem

Populate IsBundled field for each document to true, if a checksum matches more than 1 documents. In our case 1st and 2nd documents needs to updated with isBundled: true . Instead of adding this logic in application code, I am looking for better solutions using aggregation pipeline

2

Answers


  1. Maybe something like this:

    db.collection.aggregate([
    {
    "$group": {
      "_id": "$checksum",
       "toUpdate": {
        "$addToSet": "$_id"
       },
      cnt: {
        $sum: 1
        }
      }
      },
      {
       $match: {
        cnt: {
          $gt: 1
       }
      }
     },
     {
      $unwind: "$toUpdate"
     }
     ]).toArray().forEach(function(d){ db.collection.update({_id:d.toUpdate},{$set:{ IsBundled:"true" }})   })
    

    aggregation playground

    Explained:

    1. Group on checksum and get document _id per same checksum
    2. Filter checksum matching more then one document
    3. Unwind toUpdate array with the _id’s needed to be updated
    4. Loop over the result to update all the documents with IsBundled: true
    Login or Signup to reply.
  2. MongoDb Playground link : https://mongoplayground.net/p/pV_UbQ-ADby

    $group: To group the matching documents.
    $set: To modify the document
    $gt: To check if greater than condition
    $replaceRoot: To replace the current document structure by another.

    db.collection.aggregate([
      {
        $group: {
          _id: "$checksum",
          count: {
            $sum: 1
          },
          bundles: {
            $push: "$$ROOT"
          }
        }
      },
      {
        "$unwind": "$bundles"
      },
      {
        $set: {
          "bundles.IsBundled": {
            $gt: [
              "$count",
              1
            ]
          }
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$bundles"
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search