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.
2 Answers
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);
});
Comments
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
1 Comment
Community
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.