c# - MongoDB 更新文档并添加新属性

标签 c# mongodb

我正在使用 C# 3.2 驱动程序并尝试插入或更新文档,并且(可能)添加一些新字段。我的代码如下所示:

var collection = database.GetCollection<BsonDocument>("User");
var filter = Builders<BsonDocument>.Filter.Eq("UserID", "mkemp");

var update = Builders<BsonDocument>.Update
        .Set("FirstName", "Mike")
        .Set("LastName", "Kemp");


update.AddToSet("Age", "57");

var result = collection.UpdateOne(filter, update , new UpdateOptions() { IsUpsert = true });

已创建 FirstName 和 LastName,但未创建或更新 Age 字段。我正在根据表单发布保存数据,因此我事先不知道将发布哪些字段。有没有什么办法可以实现上面的功能呢?

最佳答案

这比您想象的要容易:在 Mongo 中,如果属性不存在,则会创建它。

AddToSet 不是设置简单的值,而是将项目添加到存储在给定属性名称中的数组中,并且它实现 set 语义。也就是说,如果您使用 AddToSet 添加项目,您将创建一个唯一项目数组 ( taken from Mongo docs ):

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

查看以下docs for $set:

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

关于c# - MongoDB 更新文档并添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561732/

相关文章:

python - 每个文档中 ISODate 之间的差异?

mongodb - 在一个查询中查找最接近的日期

node.js - 在 Mongoose 中使用某些条件查找时获取空数组

c# - 在 Knockout foreach 数据绑定(bind)中使用服务器端对象类型

c# - Windows Form C#的本地化

c# - 从 C# 代码隐藏中删除事件时,如何自动删除 asp.net webcontrol 中的事件引用?

c# - 如何使用 Win2D 模拟 DeviceLost 事件?

c# - 将 System.Drawing.Image 转换为格式 (.jpeg .gif) 而无需保存

javascript - 使用过滤器以自定义格式设置日期格式

mongodb - 将 Mongodb 数据库移动到不同的驱动器 : Unable to acquire lock for lockfilepath