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, othe
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 );
[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); }
collection.update
with upsert:true
. See also here.
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)