How can I add a new field to every document in an existent collection?
I know how to update an existing document’s field but not how to add a new field to every document in a collection. How can I do this in the mongo shell?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Same as the updating existing collection field,
$setwill add a new fields if the specified field does not exist.Check out this example:
EDIT:
In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents
EDIT:
In the above example last 2 fields
false, truespecifies theupsertandmultiflags.Upsert: If set to true, creates a new document when no document matches the query criteria.
Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.
This is for Mongo
versionsprior to2.2. For latest versions the query is changed a bit