How to update if exists otherwise insert new document?

MongodbMongoose

Mongodb Problem Overview


How to update if exists otherwise insert new document in javascript/node.js? I am getting as parameter to function dictionary,if dictionary contains _id should update, otherwise insert on remote server (I have connection with remote server through mongoose and I have Person schema which I want to insert/update).

Mongodb Solutions


Solution 1 - Mongodb

In Mongoose, you'd use Person.update per the documentation. In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false.

i.e.

Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );

Solution 2 - Mongodb

collection.update with upsert:true. See also here.

Solution 3 - Mongodb

[db.collection.replaceOne(filter, replacement, options)] with upsert:true

E.g. from here:

try {    db.restaurant.replaceOne(
            { "name" : "Pizza Rat's Pizzaria" },
            { "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 },
            { upsert: true }    
         ); 
    }
catch (e){ print(e); }

Solution 4 - Mongodb

For python:

import pymongo

client = pymongo.MongoClient("mongodb_address")
db = client.db_name
collection = db[collection_name]

# update 'data' if 'name' exists otherwise insert new document
collection.find_one_and_update({"name": some_name},
                               {"$set": {"data": some_data}},
                               upsert=True)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaolaJ.View Question on Stackoverflow
Solution 1 - MongodbEmptyArsenalView Answer on Stackoverflow
Solution 2 - MongodbheinobView Answer on Stackoverflow
Solution 3 - Mongodbhru_dView Answer on Stackoverflow
Solution 4 - Mongodbbanderlog013View Answer on Stackoverflow