How to update if exists otherwise insert new document?

前端 未结 4 1849
执笔经年
执笔经年 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条回答
  •  夕颜
    夕颜 (楼主)
    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)
    

提交回复
热议问题