I want to replace a document when this already exists and if it doesn't I want it inserted. How can I do that in mongoDb?
I need something like this, but in one query:
find by a "where statement"
if exists, replace whole document
else, insert
Thank you!
How to update a MongoDB document without overwriting the existing one? To update only a field value, use update () along with $set. This won’t overwrite the existing one.
When true, replaceOne () either: Inserts the document from the replacement parameter if no document matches the filter. Replaces the document that matches the filter with the replacement document. MongoDB will add the _id field to the replacement document if it is not specified in either the filter or replacement documents.
If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. This also applies to documents inserted through update operations with upsert: true.
See Insert Behavior. insertMany () returns a document that includes the newly inserted documents _id field values. See the reference for an example. If the collection does not currently exist, insert operations will create the collection. In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key.
you could also use the save operation, that is much faster than the update (x70 faster from my tests), and is adapt to your purpose, but in case remember to give in input the whole document
Use collection update.
In the example below, the first update call will "insert or replace" the document (including name field from the query). In the second the update call will insert the document or just update Joe's job leaving the rest of the document intact. The difference is the "$set" operation.
<?php
$c->update(
array("name" => "joe"),
array("username" => "joe312", "job" => "Codemonkey"),
array("upsert" => true));
$c->update(
array("name" => "joe"),
array("$set" => array("job" => "Bartender")),
array("upsert" => true));
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With