How to update if exists otherwise insert new document?

前端 未结 4 1826
执笔经年
执笔经年 2020-12-02 20:14

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

相关标签:
4条回答
  • 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 );
    
    0 讨论(0)
  • 2020-12-02 20:37

    [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); }
    
    0 讨论(0)
  • 2020-12-02 20:46

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

    0 讨论(0)
  • 2020-12-02 20:47

    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)
    
    0 讨论(0)
提交回复
热议问题