mongodb: upserting: only set value if document is being inserted

后端 未结 4 773
不知归路
不知归路 2021-01-03 22:12

Considering a simple mongo document structure:

{ _id, firstTime, lastTime }

The client needs to insert a document with a known ID, or update an existing docu

4条回答
  •  醉话见心
    2021-01-03 22:21

    I ran into a very similar problem when attempting to upsert documents based on existing content--maybe this solution will work for you also:

    Try removing the _id attribute from your record and only use it in the query portion of your update (you'll have to translate from pymongo speak...)

    myid = doc.get('_id')
    del doc['_id']
    mycollection.update({'_id':myid}, {'$set':doc}, upsert=True)
    

提交回复
热议问题