如何使用 C# 驱动程序更新和更新插入 MongoDB 中的多个文档

发布于 2024-12-12 17:00:32 字数 142 浏览 0 评论 0原文

我正在使用 MongoDB 2,我想更新多个文档并更新插入像 processed:true 这样的值 进入收藏。但是 MongoDB c# api 只允许我们更新多个记录或更新插入单个记录。

如何使用C# api解决这个问题?

I am using MongoDB 2, and I want to update multiple documents and upsert a value like processed:true
into the collection. But MongoDB c# api only allows us to either Update Multiple Records or Upsert a single record.

How to solve this problem using the C# api?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

挽心 2024-12-19 17:00:35

使用 [email protected] - 尝试initializeUnorderedBulkOp():

export const InfoFunc = (Infos: Infos[]) => {

  const bulk = InfoResult.collection.initializeUnorderedBulkOp();
  Infos.forEach((info: Infos) => bulk.find({ "Id": info.Id}).upsert().updateOne(info));
  bulk.execute();
}

Working with [email protected] - try initializeUnorderedBulkOp():

export const InfoFunc = (Infos: Infos[]) => {

  const bulk = InfoResult.collection.initializeUnorderedBulkOp();
  Infos.forEach((info: Infos) => bulk.find({ "Id": info.Id}).upsert().updateOne(info));
  bulk.execute();
}
殊姿 2024-12-19 17:00:34

尝试首先从集合中删除要插入的所有项目,然后调用 insert:

        var search = [];
        arrayToInsert.forEach(function(v, k) {
            search.push(v.hash); // my unique key is hash. you could use _id or whatever
        })
        collection.remove({
            'hash' : {
                $in : search
            }
        }, function(e, docs) {

            collection.insert(arrayToInsert, function(e, docs) {
                if (e) {
                    console.log("data failed to update ", e);
                }
                else {
                    console.log("data updated ");
                }
            });
        })

Try first removing all items to be inserted from the collection, and then calling insert:

        var search = [];
        arrayToInsert.forEach(function(v, k) {
            search.push(v.hash); // my unique key is hash. you could use _id or whatever
        })
        collection.remove({
            'hash' : {
                $in : search
            }
        }, function(e, docs) {

            collection.insert(arrayToInsert, function(e, docs) {
                if (e) {
                    console.log("data failed to update ", e);
                }
                else {
                    console.log("data updated ");
                }
            });
        })
两人的回忆 2024-12-19 17:00:34

更漂亮、更健壮的方法:

public interface IProjection
{
    Guid Id { get; }
    bool IsDeleted { get; }
}
public async Task UpsertManyAsync<TProjection>(IEnumerable<TProjection> replacements, CancellationToken cancellationToken)
    where TProjection : IProjection
{
    var requests = replacements.Select(replacement => new ReplaceOneModel<TProjection>(
        filter: new ExpressionFilterDefinition<TProjection>(projection => projection.Id == replacement.Id),
        replacement: replacement) { IsUpsert = true });

    await _context
        .GetCollection<TProjection>()
        .BulkWriteAsync(
            requests: requests,
            options: new BulkWriteOptions { IsOrdered = false },
            cancellationToken: cancellationToken);
}

A prettier and more robust approach:

public interface IProjection
{
    Guid Id { get; }
    bool IsDeleted { get; }
}
public async Task UpsertManyAsync<TProjection>(IEnumerable<TProjection> replacements, CancellationToken cancellationToken)
    where TProjection : IProjection
{
    var requests = replacements.Select(replacement => new ReplaceOneModel<TProjection>(
        filter: new ExpressionFilterDefinition<TProjection>(projection => projection.Id == replacement.Id),
        replacement: replacement) { IsUpsert = true });

    await _context
        .GetCollection<TProjection>()
        .BulkWriteAsync(
            requests: requests,
            options: new BulkWriteOptions { IsOrdered = false },
            cancellationToken: cancellationToken);
}
素食主义者 2024-12-19 17:00:34

UpdateFlags 是 C# 驱动程序中的一个枚举,可让您同时指定两者。就像任何其他标志枚举一样,您可以通过位“或”来完成此操作。

var flags = UpdateFlags.Upsert | UpdateFlags.Multi;

您可以在此处阅读有关枚举的文档(http://msdn.microsoft.com/en-us/library/cc138362.aspx),特别注意有关枚举类型作为位标志的部分

UpdateFlags is an enum in the C# driver that will let you specify both at once. Just like any other flags enum, you do this by bit "or"ing.

var flags = UpdateFlags.Upsert | UpdateFlags.Multi;

You can read the docs on enums here (http://msdn.microsoft.com/en-us/library/cc138362.aspx) paying special attention to the section on Enumeration Types as Bit Flags

紫瑟鸿黎 2024-12-19 17:00:32

Mongo 2.6 之后,您可以执行批量更新/Upserts。下面的示例使用 c# 驱动程序进行批量更新。

MongoCollection<foo> collection = database.GetCollection<foo>(collectionName);
      var bulk = collection.InitializeUnorderedBulkOperation();
      foreach (FooDoc fooDoc in fooDocsList)
      {
        var update = new UpdateDocument { {fooDoc.ToBsonDocument() } };
        bulk.Find(Query.EQ("_id", fooDoc.Id)).Upsert().UpdateOne(update);
      }
      BulkWriteResult bwr =  bulk.Execute();

After Mongo 2.6 you can do Bulk Updates/Upserts. Example below does bulk update using c# driver.

MongoCollection<foo> collection = database.GetCollection<foo>(collectionName);
      var bulk = collection.InitializeUnorderedBulkOperation();
      foreach (FooDoc fooDoc in fooDocsList)
      {
        var update = new UpdateDocument { {fooDoc.ToBsonDocument() } };
        bulk.Find(Query.EQ("_id", fooDoc.Id)).Upsert().UpdateOne(update);
      }
      BulkWriteResult bwr =  bulk.Execute();
相权↑美人 2024-12-19 17:00:32

你不能在一份声明中做到这一点。

您有两个选择

1) 循环所有对象并进行更新插入

2) 找出哪些对象必须更新以及哪些对象必须插入,然后进行批量插入和多重更新

You cannot do it in one statement.

You have two options

1) loop over all the objects and do upserts

2) figure out which objects have to get updated and which have to be inserted then do a batch insert and a multi update

我偏爱纯白色 2024-12-19 17:00:32

对于使用 2.0 版 MongoDB.Driver 的用户,您可以使用 BulkWriteAsync 方法。

<!-- language: c# -->
// our example list
List<Products> products = GetProductsFromSomewhere();  

var collection = YourDatabase.GetCollection<BsonDocument>("products"); 

// initialise write model to hold list of our upsert tasks
var models = new WriteModel<BsonDocument>[products.Count];

// use ReplaceOneModel with property IsUpsert set to true to upsert whole documents
for (var i = 0; i < products.Count; i++){
    var bsonDoc = products[i].ToBsonDocument();
    models[i] = new ReplaceOneModel<BsonDocument>(new BsonDocument("aw_product_id", products[i].aw_product_id), bsonDoc) { IsUpsert = true };
};

await collection.BulkWriteAsync(models); 

For those using version 2.0 of the MongoDB.Driver, you can make use of the BulkWriteAsync method.

<!-- language: c# -->
// our example list
List<Products> products = GetProductsFromSomewhere();  

var collection = YourDatabase.GetCollection<BsonDocument>("products"); 

// initialise write model to hold list of our upsert tasks
var models = new WriteModel<BsonDocument>[products.Count];

// use ReplaceOneModel with property IsUpsert set to true to upsert whole documents
for (var i = 0; i < products.Count; i++){
    var bsonDoc = products[i].ToBsonDocument();
    models[i] = new ReplaceOneModel<BsonDocument>(new BsonDocument("aw_product_id", products[i].aw_product_id), bsonDoc) { IsUpsert = true };
};

await collection.BulkWriteAsync(models); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文