1

I have collection with 50 documents. Is is possible to add one key (the same to all of them) and the value of this key is increment from 1 to 50. I mean for example the first document have a key: myId=1 , the second document myId=2 and so on.

Community
  • 1
  • 1
Josef
  • 87
  • 8

2 Answers2

6

You can write a script inside the shell to loop through all the documents and run an update query for each document to add a new field.

This is how you could add a field to collection: Add new field to a collection in MongoDB

Referring the link above I wrote this, it should probably help

var i = 0;
db.collection.find().forEach(function(myDoc) {
    db.collection.update(myDoc, {$set : {"myId": i++ }}, false, true);  
});
Community
  • 1
  • 1
jayeshsolanki93
  • 2,046
  • 1
  • 18
  • 37
0
var i=0;
db.collection.find().forEach(function(my){db.collection.update(my,{$set:{"newfield":i++}})})

It is still working with out the false and true flags of upsert and multi

General Grievance
  • 4,259
  • 21
  • 28
  • 43
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 13 '22 at 20:09