sterling sterling - 21 days ago 5
PHP Question

How do you update a mongodb document while replacing the entire document?

If I have a document with two values:

{
"name" : "Bob",
"location" "France"
}


And then pass an array to the document that contains "name", "country". How do I ensure that the entire document is updated, with "location" removed?

I will not be aware of the differences between the two documents, so I wont be able to unset a specific field. I am looking for a method to simply replace the document data with the array supplied.

Answer

If you supply update with a new document containing the records you want, you will replace the document.

For example:

db.so.insert({"name":"Bob", "location": "France"})
db.so.update({"name":"Bob", "location": "France"}, {"name":"Roberto", "country":"Italy"})
db.so.find()

{ "_id" : ObjectId(), "name" : "Roberto", "country" : "Italy" }

Of course, if you had the _id of the document, this would be a better way of specifying the update (rather than passing back the document you just inserted like above)

Comments