Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Insert Field to all documents in a collection

Tags:

mongodb

I am trying to add a new field into all documents in an existing collection.

Database name = test Collection name = teams

test.teams.update({
}
,
{
    $set: {
        "isGolden": false
    }
}
,
false,
true)

When I am trying it with MongoChef, it is giving me the following error: enter image description here

What is wrong with this? Thanks

like image 908
Val Nolav Avatar asked Nov 11 '15 12:11

Val Nolav


People also ask

How do I add a field to a collection in MongoDB?

To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .

How do I add multiple values to a collection in MongoDB?

insertMany() method. insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field.

What function inserts multiple documents into a collection?

db. collection. insertMany() can insert multiple documents into a collection.

How do you create a collection and insert data in MongoDB?

Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it. In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.


2 Answers

If you want to update all the documents, use something like this:

db.teams.update({}, {$set: {isGolden: false}}, {multi: true});

your are selecting all, setting the field isGolden to false and making this update in all documents using multi: true

like image 132
rcmgleite Avatar answered Nov 15 '22 20:11

rcmgleite


With Studio 3T you were writing queries in JSON mode in which it wants JSON data but you are not writing JSON Query. You must go to InteliShell mode in which your query will execute in format that you were writing.

Studio 3T InteliShell

like image 44
Parth Chauhan Avatar answered Nov 15 '22 21:11

Parth Chauhan