Mongodb upsert only update selected fields, but insert all

后端 未结 2 1886
不知归路
不知归路 2020-12-30 05:31

I am trying to use upsert in MongoDB to update a single field in a document if found OR insert a whole new document with lots of fields. The problem is that it appears to me

2条回答
  •  长发绾君心
    2020-12-30 06:19

    MongoDB 2.4 has $setOnInsert

    db.somecollection.update(
        {name: "some name"},
        {
            $set: {
                "lastseen": "2012-12-28"
            },
            $setOnInsert: {
                "firstseen":   # set on insert, not on update
            }
        },
        {upsert:true}
    )
    

提交回复
热议问题