单个MongoDB实例上的C#MongoDB驱动程序事务

单个MongoDB实例上的C#MongoDB驱动程序事务,c#,mongodb,C#,Mongodb,我正在使用MongoDB 4.0.8和C#driver 2.8.1,并试图在我的项目中实现事务。 我复制粘贴了以下代码示例: static async Task<bool> UpdateProducts() { //Create client connection to our MongoDB database var client = new MongoClient(MongoDBConnectionString); //Create a session

我正在使用MongoDB 4.0.8和C#driver 2.8.1,并试图在我的项目中实现
事务。
我复制粘贴了以下代码示例:

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;
}
报告说:

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


我的项目中没有副本,我只有一个数据库实例,它是我的主要数据库实例。是否有一个解决方案或变通方法可用于实施
事务
?我有一些方法可以更新多个集合,我真的认为这可以节省我使用它的时间。

正如文档所述,事务只适用于副本集。因此,您需要将mongodb服务器作为单节点副本集运行。要实现这一点,请执行以下步骤

第1步: 停止mongodb服务器

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

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并发出以下命令以启动副本集

rs.initiate()
步骤4:重新启动mongod


另外,如果您想编写更干净、更方便的事务代码,请查看我的库

使用(var TN=new Transaction())
{
var author=新作者{Name=“one”};
TN.Save(作者);
TN.Delete(book.ID);
TN.Commit();
}

请参见注释2:出于开发目的,您可以使用一个节点启动副本集。启动mongod-replSet,然后在mongoshell中执行rs.initiate()。请注意,这不是生产环境的推荐设置。@LiranFriedman我假设您使用的是
mongod.cfg
文件。本质上是一样的。
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