MongoDb replacing a document and inserting when non-existant
Asked Answered
N

2

7

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!

Nightingale answered 6/11, 2013 at 14:6 Comment(0)
Y
1

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

?>
Yockey answered 6/11, 2013 at 14:29 Comment(0)
A
5

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

Atp answered 9/12, 2013 at 14:13 Comment(2)
But if the document exists, save creates a new duplicate?Schizont
@Schizont Per the documentation for MongoDB (linked above for "save") - "If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field." - So, no, if the document exists, as long as you're providing the same "_id", then no duplicate is created.Malia
Y
1

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

?>
Yockey answered 6/11, 2013 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.