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

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

    I ran into the exact same problem and there was no simple solution for <2.4 however since 2.4 the $setOnInsert operator let's you do exactly that.

    db.collection.update( ,
                          { $setOnInsert: { "firstTime":  } },
                          { upsert: true }
                        )
    

    See the 2.4 release notes of setOnInsert for more info.

提交回复
热议问题