c# - Mongo DB中的Upserting和Id问题

标签 c# mongodb mongodb-.net-driver

我在使用官方 C# 驱动程序升级到 mongo db 时遇到问题。

public abstract class AggregateRoot
{
    /// <summary>
    /// All mongoDb documents must have an id, we specify it here
    /// </summary>
    protected AggregateRoot()
    {
        Id = ObjectId.GenerateNewId();
    }

    [BsonId]
    public ObjectId Id { get; set; }
}

我的实体已经有 id-s,但我必须创建 mongo 特定的 Id 才能工作,因为集合中的所有文档都应该有一个。现在我在我的系统中收到一个新实体,生成了一个新的 Mongo Id,我得到 mongo cannot change _id of a document old 异常。有什么解决办法吗?

Let me describe the design a bit. All the entities which would be stored as documents were inheriting from AggregateRoot which had the id generation in it. Every sub-document had its id generated automatically and I had no problem with this. The id in AggregateRoot was introduced to correct the problem when retrieving data from MongoCollection to List and the generation was introduced so the id-s are different. Now we can move that id generation to save methods because the new entity for update had a new id generation. But it would mean that every dev on the team must not forget generating id-s in repository which is risky. It would be nicer just to ignore the id than mapping from mongo if it is possible and not to have AggregateRoot class at all

最佳答案

我也遇到过类似的问题。 我想使用官方 C# 驱动程序更新文档。我有这样的课:

public class MyClass
{
    public ObjectId Id { get; set; }
    public int Field1 { get; set; }
    public string Field2 { get; set; }
}

在控制台中我会写: db.collection.update({Field1: 3},{Field1: 3, Field2: "value"}) 它会起作用。我在 C# 中写道:

collection.Update(Query.EQ("Field1", 3),
                Update.Replace(new MyClass { Field1 = 3, Field2 = "value" }),
                UpdateFlags.Upsert);

它没有用!因为驱动程序在更新语句中包含空 id,并且当我插入第二个具有不同值的文档时 Field1 异常 E11000 duplicate key error index 被抛出(在这种情况下,Mongo 尝试插入一个 _id 已经存在的文档分贝)。

当我自己生成 _id(如主题启动器)时,我在更新插入现有值为 Field1 的对象时遇到了相同的异常(mongo 无法更改文档的 _id)。

解决方案是通过[BsonIgnoreIfDefault]属性标记Id属性(不初始化)。在这种情况下,驱动程序会在更新语句中省略 _id 字段,MongoDb 会在必要时生成 Id。

关于c# - Mongo DB中的Upserting和Id问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7283156/

相关文章:

c# - C# 中的 MongoDB FilterDefinition 和接口(interface)

c# - 如何在C#中获取连接字符串中指定的Mongo数据库

c# - 装箱值只是指向存储在托管堆中的值副本的指针吗?

c# - 更改 List<Texture> 的项目会创建一个新项目

node.js - 检查数组中是否存在所有元素

node.js - node-mongodb-native:如何通过我的应用程序共享连接回调的 db api 对象

c# - 双击文本区域或文本框时指定突出显示行为?

c# - ASP.NET MVC : Get lowercase links (instead of Camel Case)

mongodb - 如何通过比较子字段构造 MongoDB Linq Any() 查询

mongodb - 从近查询中检索距离 "dis"结果