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.
Asked
Active
Viewed 2,084 times
2 Answers
7
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,096
- 1
- 20
- 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,555
- 31
- 31
- 45

Saikrishna Vs
- 1
- 2
-
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