1

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.

Ali Celebi
  • 824
  • 1
  • 10
  • 19

1 Answers1

3

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

Rishabh Agarwal
  • 1,988
  • 1
  • 16
  • 33
  • You can update the queries as you want. I considered null in place of "". @HadidAli, you can update queries accordingly. Hope you got the methodology I want to convey. – Rishabh Agarwal Sep 25 '18 at 19:15
  • Thanks that works but there's glitch. Both properties are updated with a decimal point at the end. How can I resolve this issue? "outletID" : 32000.0, "companyID" : 51000.0 – Ali Celebi Sep 25 '18 at 19:35
  • There shouldn't be. You can see my output. can You share your script. – Rishabh Agarwal Sep 25 '18 at 19:43
  • var val_outletID = 32; var val_companyID = 51; db.dealers.find().forEach( function(elem) { db.dealers.update( { "outletID" : null, "companyID" : null}, {$set:{ outletID: val_outletID , companyID: val_companyID } }); val_outletID++; val_companyID++; }); – Ali Celebi Sep 25 '18 at 19:49
  • Hey @HadidAli can you try this: https://stackoverflow.com/questions/8218484/mongodb-inserts-float-when-trying-to-insert-integer – Rishabh Agarwal Sep 25 '18 at 19:54