Ali Celebi
Ali Celebi

Reputation: 1000

MongoDB - update a property with incremental values

I have a collection called dealers as follows.

{
    "_id" : ObjectId("5b9ba196cd5f5af83bb0dc71"),
    "name" : "SOME COMPANY",
    "outletID" : "GS0061920",
    "companyID" : "GC0050397"
}

I have about 5000 documents in this collection where outletID and companyID properties are empty.

I would like to update both of these properties for all documents in this collection with incremental values.

I'm not sure how I should go about this.

Note: MongoDB 3.4 is in use.

Upvotes: 1

Views: 111

Answers (1)

Rishabh Agarwal
Rishabh Agarwal

Reputation: 2172

Assuming you are running on mongodb shell. You can use the following:

> var counter = 1;
> db.collection.find().forEach(
      function(elem) { 
        db.myColl.update(
          { "outletID" : null, "companyID" : null}, 
          {$set:{ outletID: counter , companyID: counter } 
          }); 
       counter++;
     });

The mongo shell is an interactive JavaScript interface. I have used JS for the task. counter is a simple variable which is used to update values. $set is used to update the fields.

The $set operator replaces the value of a field with the specified value. You can find more data in its official documentation.

I created a sample data and tested my function. Hope it works fine. Image showing the commands I ran in shell

Upvotes: 3

Related Questions