带有C#的Mongo DB-添加文档而与事务无关 [英] Mongo DB with C# - document added regardless of transaction
问题描述
我正在尝试用我编写的一个简单示例测试Mongo DB中新支持的事务. 我正在将Mongo DB版本4.0.5与驱动程序版本2.8.1结合使用. 这只是一个没有分片/副本的主实例.
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote. I'm using Mongo DB version 4.0.5 with driver version 2.8.1. It's only a primary instance with no shards/replicas.
我必须在以下代码中缺少一些基本知识.
我创建一个Mongo客户,会话&数据库,然后开始事务,添加文档并中止该事务.在此代码之后,我希望数据库中没有任何更改,但已添加了文档.调试时,我还可以使用Robo 3T(Mongo客户端GUI)在InsertOne()
之后立即看到文档.
I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne()
by using Robo 3T (Mongo client GUI).
知道我想念什么吗?
var client = new MongoClient("mongodb://localhost:27017");
var session = client.StartSession();
var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
{
GuidRepresentation = GuidRepresentation.Standard,
ReadPreference = ReadPreference.Primary,
WriteConcern = new WriteConcern(1,
new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),
});
var entities = database.GetCollection<MyEntity>("test");
session.StartTransaction();
// After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
entities.InsertOne(new MyEntity { Name = "Entity" });
// This does not have any effect
session.AbortTransaction();
可以将MongoDB作为1节点副本集运行,尽管我不确定独立副本和1节点副本集有什么区别. 请参阅下面的我的帖子.
It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set. See my post below.
无论如何,要使用已启动的事务,插入代码必须将会话作为参数接收:
In any case, to use the started transaction the insertion code must receive the session as a parameter:
entities.InsertOne(session, new MyEntity { Name = "Entity" });
现在有了这两项更改,交易就可以了.
With these 2 change now the transaction works.
推荐答案
这本质上是MongoDB本身的属性. (更多此处和
This is inherently a property of MongoDB itself. (More here and here)
交易仅在副本集设置中可用
Transactions are only available in a replica set setup
为什么它不能用于独立实例?
借助子文档和数组,文档数据库(MongoDB)允许相关数据在单个数据结构内按层次结构进行统一.可以使用原子操作来更新文档,从而为文档提供与关系数据库中的多表事务相同的数据完整性保证.
这篇关于带有C#的Mongo DB-添加文档而与事务无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!