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.

2 Answers 2

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);  
});
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.