Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mongodb

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.

like image 714
sterling Avatar asked Feb 04 '26 13:02

sterling


1 Answers

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)

like image 176
Andre de Frere Avatar answered Feb 06 '26 02:02

Andre de Frere