MongoDB: update only specific fields

后端 未结 4 1362
醉酒成梦
醉酒成梦 2021-01-11 12:22

I am trying to update a row in a (typed) MongoDB collection with the C# driver. When handling data of that particular collection of type MongoCollection

4条回答
  •  攒了一身酷
    2021-01-11 12:46

    Save(someValue) is for the case where you want the resulting record to be or become the full object (someValue) you passed in.

    You can use

    var query = Query.EQ("_id","123");
    var sortBy = SortBy.Null;
    var update = Update.Inc("LoginCount",1).Set("LastLogin",DateTime.UtcNow); // some update, you can chain a series of update commands here
    
    MongoCollection.FindAndModify(query,sortby,update); 
    

    method.

    Using FindAndModify you can specify exactly which fields in an existing record to change and leave the rest alone.

    You can see an example here.

    The only thing you need from the existing record would be its _id, the 2 secret fields need not be loaded or ever mapped back into your POCO object.

提交回复
热议问题