Patrik Krehák
Patrik Krehák

Reputation: 2683

Update value in MongoDB

I have to add new value (or edit actual) company. I tried this code in console:

db.users.update({email: /debute/},{company: "test"})

But now, in database I have only _id and company. Why other values removed? Or how can I prevent of removing other values in future?

Upvotes: 0

Views: 199

Answers (2)

Martin
Martin

Reputation: 5332

You need to use an update operator on order to update an existing document, your code replaces the document with the new document. Here is how to do an update:

db.users.update({email: /debute/},{$set: {company: "test"}})

Upvotes: 2

Philipp
Philipp

Reputation: 69703

By default, the update function replaces the entire document with the document you pass. But you can also use it to only replace individual fields and leave the others alone by using the $set operator.

db.users.update({email: /debute/},{ $set: { company: "test"} } );

You might also want to specify a third argument { multi: true } to the update. Otherwise it will only update the first document it finds which matches the condition.

Upvotes: 3

Related Questions