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

后端 未结 4 748
不知归路
不知归路 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:18

    If you will trigger the following code 2 subsequent times, it will first set both firstVisit and lastVisit on document insert (and will return upsertedId in the response) and on the second it will only update lastVisit (and will return modifiedCount: 1).

    Tested with Mongo 4.0.5 though I believe should be working with older versions.

    db.collection.updateOne(
      {_id: 1}, 
      { 
        $set: { 
          lastVisit: Date.now() 
        }, 
        $setOnInsert: {
          firstVisit: Date.now()
        }
      }, 
      { upsert: true }
    );
    

提交回复
热议问题