Is it possible to add a field to every document in a collection in MongoDB Compass?
Asked Answered
N

2

9

Is it possible to add a field to every document in a collection in MongoDB Compass? Or is this something that has to be done in the shell?

Nanettenani answered 25/11, 2019 at 18:26 Comment(0)
P
9

There is no option in Compass to update all documents with a new field; Compass's "Document tab" has option to modify a document's field or add a new field (modify one document at a time).

This is to be done from the mongo shell or your favorite programming language.

From the shell, to update all documents in a collection with a new field use the db.collection.updateMany() method. For example, db.test.updateMany( { }, { $set: { new_field: "initial value" } } ).

Once, the documents are updated, these can be viewed from the Compass; just do a refresh in the Documents view / tab.

Pretence answered 26/11, 2019 at 1:54 Comment(1)
this simply worksBootlace
I
1

There is now an option available in MongoDB compass to update every document inside a collection.

  1. Select the desired collection and click on update button.
  2. A dialog box will appear which will show JSON to set the values.
  3. Add the values in JSON format and update.
{
  $set: {
    keyname: value
  },
}
Ironlike answered 5/4 at 5:16 Comment(1)
Also, see MongoDB Compass - Modify Multiple Documents. This feature is introduced with Compass version 1.42.0 (released January 31, 2024).Pretence

© 2022 - 2024 — McMap. All rights reserved.