mongodbmongodb-queryphp-mongodbmongodb-update

Mongo update while excluding certain fields


This sounds like it would be similar to a Mongo $set. In this case, I would like to update the document (update and/or delete fields) but ignore the field creatorName, keeping it the same.

Example document:

{id: 1, firstName: 'Testy', middleName: 'Jim', lastName: 'Shorts', creatorName: 'User1'}

Updated to:

{id: 1, firstName: 'Production', lastName: 'Pants', creatorName: 'User1'}

If I use set, creatorName remains the same (good) and firstName and lastName are updated (good), but middleName is not deleted (bad). Set limits the ability to remove a field during an update.

Can this be done in a query? Without $unset?


Solution

  • It sounds like there might be more complicated stuff going on, but you've only hinted at it in the comments so I can't really speak to it. There is, however, a good way to do what you want with the name situation. Store the name fields as an embedded object and update the object:

    > db.characters.findOne()
    {
        "_id" : ObjectId("53f6293de062d5cdbec6553e"),
        "creatorName" : "Stan Smalls",
        "name" : {
            "first" : "Jack",
            "middle" : "B",
            "last" : "Quick"
        }
    }
    > db.characters.update({ "_id" : ObjectId("53f6293de062d5cdbec6553e") },
        { "$set" : {
            "name" : {
                "first" : "Sam",
                "last" : "Slow"
                }
            }
        }) 
    > db.characters.findOne()
    {
        "_id" : ObjectId("53f6293de062d5cdbec6553e"),
        "creatorName" : "Stan Smalls",
        "name" : {
            "first" : "Sam",
            "last" : "Slow"
        }
    }
    

    The larger principle you might be able to apply to your more complicated case is to group together fields that need to be updated with those that need to be removed whenever the related fields are updated inside an embedded document, so you can re-$set the document and effectively update some fields while default removing some fields and preserving others.