Home > Mobile >  Update many document based on a condition MongoDB
Update many document based on a condition MongoDB

Time:04-26

Here's my schema

{ _id : Number,
  user1: {
   _id : Number, 
   userDetail : {
    userId : Number,
    userResult : String,
   }
  }, 
  user2 : {
   _id : Number, 
   userDetail : {
    userId : Number,
    userResult : String,
   }
  },
 createdAt : Date, 
 updatedAt : Date
}

Sample Doc look like this

{
    "_id" : ObjectId("625ebcabcc03685c273b2363"),
    "user1" : {
        "_id" : "625ebc9fcc03685c273b2207",
        "userDetail" : {
            "userId" : 7,
            "userResult" : "won"
        }
    },
    "user2" : {
        "_id" : "625ebc9fcc03685c273b2208",
        "userDetail" : {
            "userId" : 11,
            "userResult" : "lose"
        }
    },
    "createdAt" : ISODate("2022-04-19T13:44:11.781Z"),
    "updatedAt" : ISODate("2022-04-19T13:44:11.781Z")
}

Now I have nearly 1000 doc where this user has played. So I need to update the userId of all this users. How I am able to do this. I am getting all the user by

db.getCollection('matches').find({$or : [{'user1.userDetails.userId' : 7}, 
    {'user2.userDetails.userId' : 7}
]})

By the above query I am getting all the doc where userId 7 has played now I need to update the userId 7 to 10. How could I do that.

CodePudding user response:

You can use $cond:

db.collection.update({
  $or: [{"user1.userDetail.userId": 7}, {"user2.userDetail.userId": 7}]
},
[
  {
    $set: {
      "user1.userDetail.userId": {
        $cond: [{$eq: ["$user1.userDetail.userId", 7]}, 10, "$user1.userDetail.userId"]},
      "user2.userDetail.userId": {
        $cond: [{$eq: ["$user2.userDetail.userId", 7]}, 10,
          "$user2.userDetail.userId"
        ]
      }
    }
  }
],
{multi: true})

As you cna see on the playground

CodePudding user response:

Try this

db.getCollection('matches').updateMany({$or : [{"user1.userDetails.userId" : 7}, 
{"user2.userDetails.userId" : 7}]}, { $set: { "user1.userDetails.userId": 10 })
  • Related