Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : update entire document except _id using C# driver

I have to update all the fields except _id. I want to avoid to manually update the 16 fields... All the new fields are stored inside a BsonDocument

Thanks for ideas

like image 416
hotips Avatar asked Jan 15 '13 10:01

hotips


People also ask

Is it possible to update MongoDB field using value of another field?

The $set operator used to add new fields or update existing ones cannot be used together with expressions. It only takes plain values, so it is not possible to reference other fields. The traditional MongoDB update operators like $mul and $inc which would be needed here to calculate tempF are not sufficient.

Can we change _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.


2 Answers

As @Philipp hinted there is a way way to do this. You can actually use the save function ( http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Save%3CTDocument%3Emethod ) which will do what he says for you in the database end.

So imagine you have a document of:

{
    _id: {},
    d: 1
}

And that _id already exists, it will replace the previous document with this one.

Neat huh?

like image 188
Sammaye Avatar answered Oct 29 '22 17:10

Sammaye


When I understood you correctly, you have a document B with new data and you want it to completely replace document A.

In that case you can just set the _id field of document B explicitely to the value of the _id field of document A. When you then save document B, it will replace document A in the database.

When a saved document has the id of an existing document, the database will treat it like a new version of that document, not as a new document.

like image 26
Philipp Avatar answered Oct 29 '22 18:10

Philipp