Mongodb upsert only update selected fields, but insert all

后端 未结 2 1828
不知归路
不知归路 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": <TIMESTAMP>  # set on insert, not on update
            }
        },
        {upsert:true}
    )
    
    0 讨论(0)
  • 2020-12-30 06:33

    There is a feature request for this ( https://jira.mongodb.org/browse/SERVER-340 ) which is resolved in 2.3. Odd releases are actually dev releases so this will be in the 2.4 stable.

    So there is no real way in the current stable versions to do this yet. I am afraid the only method is to actually do 3 conditional queries atm: 1 to check the row, then a if to either insert or update.

    I suppose if you had real problems with lock here you could do this function with sole JS but that's evil however it would lock this update to a single thread.

    0 讨论(0)
提交回复
热议问题