【问题标题】:C# MongoDB InsertMany missing _id after insertC# MongoDB InsertMany 插入后缺少 _id
【发布时间】:2017-03-05 06:11:12
【问题描述】:

所以我有两个功能如下。 InsertOne() 函数工作正常,并且 BsonDocument 使用新创建的 _id 进行更新。但是,InsertMany() 函数不返回对象 ID。我调试了代码,没有一个单独的文档使用 _id 字段进行更新。

InsertMany() 函数确实将文档插入到数据库中,我可以看到它们都有来自 Mongo shell 的对象 ID。

我的代码中的模型没有 Id 字段。它们正在使用 MyModel.ToBsonDocument() 之类的代码进行转换。

我是否遗漏了一些东西来取回从批量插入生成的 ID?

    public string InsertOne(BsonDocument document)
    {
        MongoCollection.InsertOne(document);
        return document["_id"].ToString();
    }

    public string[] InsertMany(IEnumerable<BsonDocument> documents)
    {
        MongoCollection.InsertMany(documents);
        return documents.Select(item => Convert.ToString(item["_id"])).ToArray();
    }

编辑 - 不确定这是否是一个错误,但我刚刚意识到如果我使用列表而不是 IEnumerable,则 InsertMany() 会按预期工作。

【问题讨论】:

    标签: c# mongodb


    【解决方案1】:

    这与如何在 LINQ 中创建 IEnumerable 的集合有关。 MongoCollection.InsertMany 通过枚举并填充 _id 来实现集合的底层。但是,它是一个新集合,它不是您最初传入的 IEnumerable,这就是它没有 ID 的原因。如果您传递List,则该集合已经物化,因此它只会填充其中的字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-14
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多