MongoDB:仅更新特定字段 [英] MongoDB: update only specific fields

查看:504
本文介绍了MongoDB:仅更新特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#驱动程序更新(类型化的)MongoDB集合中的一行.在处理MongoCollection<User>类型的特定集合的数据时,我倾向于避免从集合中检索敏感数据(盐,密码哈希等)

现在,我正在尝试更新User实例.但是,我从来没有真正检索过敏感数据,因此我想在应用修改并将新数据提交到集合之前,该数据将在检索到的模型实例中(据我所知)为default(byte[]). /p>

也许我正在监督MongoDB C#驱动程序中的一些琐碎事情,如何使用MongoCollection<T>.Save(T item)而不更新诸如User.PasswordHashUser.PasswordSalt之类的特定属性?我应该首先检索完整记录,在此处更新安全"属性,然后将其写回吗?还是有一个不错的选择可以从更新中排除某些字段?

预先感谢

解决方案

Save(someValue)用于您希望结果记录成为或成为传入的完整对象(someValue)的情况.

您可以使用

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<User>.FindAndModify(query,sortby,update); 

方法.

使用FindAndModify,您可以准确地指定要更改现有记录中的哪些字段,而其余部分则不用理会.

您可以在此处看到示例.

现有记录中唯一需要的就是它的_id,这两个秘密字段不需要加载或不必映射回POCO对象.

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<User>, I tend to avoid retrieving sensitive data from the collection (salt, password hash, etc.)

Now I am trying to update a User instance. However, I never actually retrieved sensitive data in the first place, so I guess this data would be default(byte[]) in the retrieved model instance (as far as I can tell) before I apply modifications and submit the new data to the collection.

Maybe I am overseeing something trivial in the MongoDB C# driver how I can use MongoCollection<T>.Save(T item) without updating specific properties such as User.PasswordHash or User.PasswordSalt? Should I retrieve the full record first, update "safe" properties there, and write it back? Or is there a fancy option to exclude certain fields from the update?

Thanks in advance

解决方案

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<User>.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.

这篇关于MongoDB:仅更新特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆