Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb replacing a document and inserting when non-existant

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!

like image 702
Gabriel Avatar asked Nov 06 '13 14:11

Gabriel


People also ask

How to update a MongoDB document without overwriting the existing one?

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.

What is the use of replaceone() in MongoDB?

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.

What happens if the _ID field does not exist in MongoDB?

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.

How does insertmany() work in MongoDB?

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.


2 Answers

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

like image 144
lese Avatar answered Sep 24 '22 11:09

lese


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));

?>
like image 34
James White Avatar answered Sep 20 '22 11:09

James White