我正在使用 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/