MongoDB的:只更新特定字段(MongoDB: update only specific fie

2019-07-19 20:17发布

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

Answer 1:

保存(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,2个秘密领域不需要加载或曾经映射回你的POCO对象。



Answer 2:

It's可能在哪里语句添加更多指标分析。 像这样:

var db = ReferenceTreeDb.Database;
var packageCol = db.GetCollection<Package>("dotnetpackage");
var filter = Builders<Package>.Filter.Where(_ => _.packageName == packageItem.PackageName.ToLower() && _.isLatestVersion);
var update = Builders<Package>.Update.Set(_ => _.isLatestVersion, false);
var options = new FindOneAndUpdateOptions<Package>();
packageCol.FindOneAndUpdate(filter, update, options);


Answer 3:

那么有很多方法可以在更新后的值mongodb

下面是我选择更新的MongoDB集合中的字段值的最简单的方法之一。

public string UpdateData()
        {               
            string data = string.Empty;
            string param= "{$set: { name:'Developerrr New' } }";
            string filter= "{ 'name' : 'Developerrr '}";
            try
            {  
               //******get connections values from web.config file*****
                var connectionString = ConfigurationManager.AppSettings["connectionString"];
                var databseName = ConfigurationManager.AppSettings["database"];
                var tableName = ConfigurationManager.AppSettings["table"];

                //******Connect to mongodb**********
                var client = new MongoClient(connectionString);
                var dataBases = client.GetDatabase(databseName);
                var dataCollection = dataBases.GetCollection<BsonDocument>(tableName);       

                //****** convert filter and updating value to BsonDocument*******
                BsonDocument filterDoc = BsonDocument.Parse(filter);
                BsonDocument document = BsonDocument.Parse(param);

                //********Update value using UpdateOne method*****
                dataCollection.UpdateOne(filterDoc, document);                   
                data = "Success";
            }
            catch (Exception err)
            {
                data = "Failed - " + err;
            }
            return data;    
        }

希望这将帮助你:)



Answer 4:

有同样的问题,因为我想对所有类型1种的通用方法,并没有想使用反射来创建自己的实现,我结束了以下的通用解决方案(简化,以显示在同一个方法):

Task<bool> Update(string Id, T item)
{
    var serializerSettings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore
            };
    var bson = new BsonDocument() { { "$set", BsonDocument.Parse(JsonConvert.SerializeObject(item, serializerSettings)) } };
    await database.GetCollection<T>(collectionName).UpdateOneAsync(Builders<T>.Filter.Eq("Id", Id), bson);
}

笔记:

  • 确保不能更新的所有字段设置为默认值。
  • 如果您需要设置字段为默认值,则需要要么使用DefaultValueHandling.Include,或编写自定义的方法,该更新
  • 当性能问题,写使用定制更新方法Builders<T>.Update

    PS:这显然应该由MongoDB的净驱动程序实现的,但是,我找不到任何地方它在文档,也许我只是看着走错了路。



文章来源: MongoDB: update only specific fields