Search code examples
c#mongodbmongodb-.net-driver

Update MongoDB collection where field doesn't exist


I want to update every record in a collection that doesn't contain a particular field.

The following query works using Mongo shell, but I am struggling to write this using the mongoDB.Driver in .Net.

db.Comments.update(
    { MemberRoleType: { $exists: false }},
    { $set: { MemberRoleType: 4 },
    { multi: true }
)

I've attempted various methods such as follows but can't achieve the result I'm looking for :

await comments.UpdateManyAsync(c => c.MemberRoleType == 0, Builders<Comment>.Update.Set(x => x.MemberRoleType, ContentRoleType.Online)));

Solution

  • I believe you are looking for exists

    Builders<Comments>.Filter.Exists(x => x.MemberRoleType, false);
    

    You should be able to use it like so

    var filter = Builders<Comments>.Filter.Exists(x => x.MemberRoleType, false);
    await comments.UpdateManyAsync(filter, Builders<Comment>.Update.Set(x => x.MemberRoleType, ContentRoleType.Online)));
    

    Which in turn generates this query

    {
            "q": {
                "MemberRoleType": {
                    "$exists": false
                }
            },
            "u": {
                "$set": {
                    "MemberRoleType": 4
                }
            },
            "multi": true
    }