单个MongoDB实例上的C#MongoDB驱动程序事务 [英] C# MongoDB driver transactions on a single MongoDB instance

查看:575
本文介绍了单个MongoDB实例上的C#MongoDB驱动程序事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将MongoDB 4.0.8与C#驱动程序2.8.1结合使用,并且试图在我的项目中实现Transactions. 我复制粘贴了以下代码示例:

I'm using MongoDB 4.0.8 with C# driver 2.8.1 and I'm trying to implement Transactions in my project. I copy-pasted the following code sample:

static async Task<bool> UpdateProducts()
{
    //Create client connection to our MongoDB database
    var client = new MongoClient(MongoDBConnectionString);

    //Create a session object that is used when leveraging transactions
    var session = client.StartSession();

    //Create the collection object that represents the "products" collection
    var products = session.Client.GetDatabase("MongoDBStore").GetCollection<Product>("products");

    //Clean up the collection if there is data in there
    products.Database.DropCollection("products");

    //Create some sample data
    var TV = new Product { Description = "Television", SKU = 4001, Price = 2000 };
    var Book = new Product { Description = "A funny book", SKU = 43221, Price = 19.99 };
    var DogBowl = new Product { Description = "Bowl for Fido", SKU = 123, Price = 40.00 };

    //Begin transaction
    session.StartTransaction(new TransactionOptions(
                                                    readConcern: ReadConcern.Snapshot,
                                                    writeConcern: WriteConcern.WMajority));

    try
    {
        //Insert the sample data 
        await products.InsertOneAsync(session, TV);
        await products.InsertOneAsync(session, Book);
        await products.InsertOneAsync(session, DogBowl);

        var filter = new FilterDefinitionBuilder<Product>().Empty;
        var results = await products.Find(filter).ToListAsync();

        //Increase all the prices by 10% for all products
        var update = new UpdateDefinitionBuilder<Product>().Mul<Double>(r => r.Price, 1.1);
        await products.UpdateManyAsync(session, filter, update); //,options);

        //Made it here without error? Let's commit the transaction
        session.CommitTransaction();

        //Let's print the new results to the console
        Console.WriteLine("Original Prices:\n");
        results = await products.Find<Product>(filter).ToListAsync();
        foreach (Product d in results)
        {
            Console.WriteLine(String.Format("Product Name: {0}\tPrice: {1:0.00}", d.Description, d.Price));
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error writing to MongoDB: " + e.Message);
        session.AbortTransaction();
    }
    return true;
}

但是在第一个Insert命令中,出现此错误:

But in the first Insert command, I'm getting this error:

Command insert failed:
Transaction numbers are only allowed on a replica set member or mongos.

文档表示:

从版本4.0开始,MongoDB提供了针对副本集执行多文档事务的功能.

Starting in version 4.0, MongoDB provides the ability to perform multi-document transactions against replica sets.

我的项目中没有副本,我只有一个数据库实例,这是我的主要实例.如果有解决方案或解决方法,我可以用来实现Transactions吗?我有一些方法可以更新多个集合,我真的认为这可以节省我的时间来使用它.

I don't have replicas in my project, I have only one database instance which is my primary one. If there a solution or a work-around I can use to implement Transactions? I have methods that update more than one collection and I really think it could save me time to use it.

推荐答案

事务仅适用于副本集.因此,您需要将mongodb服务器作为单节点副本集运行.为此,请执行以下步骤...

like the documentation says, transactions only work with replica sets. so you need to run your mongodb server as single node replica set. to achieve that, do the following steps...

步骤1: 停止mongodb服务器.

step 1: stop the mongodb server.

第2步:replication设置添加到您的 mongod.cfg 文件中.这是我自己的例子

step 2: add the replication setting to your mongod.cfg file. here's my own as an example

storage:
  dbPath: C:\DATA
  directoryPerDB: true
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path:  C:\DATA\log\mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1

replication:
   replSetName: MyRepSet

步骤3:打开mongodb shell并发出以下命令来启动副本集.

step 3: open up a mongodb shell and issue the following command to initiate the replica set.

rs.initiate()

步骤4:重新启动mongod

step 4: restart mongod

在旁注中,如果您想编写更简洁,更方便的事务代码(如下所示),请查看我的库

on a side-note, if you'd like to write cleaner, more convenient transaction code like the following, check out my library MongoDB.Entities

    using (var TN = new Transaction())
    {
         var author = new Author { Name = "one" };

         TN.Save(author);

         TN.Delete<Book>(book.ID);

         TN.Commit();
    }

这篇关于单个MongoDB实例上的C#MongoDB驱动程序事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆