mongo 中的事務(一)

MongoDB中的事務

注意:mongo version 4.2

因爲mongo db 裏面的文檔是可以內嵌,一般對於單個集合(表)一般用不到事務,
然而對於多個集合、多個文檔、多個數據庫甚至於多個分片進行操作的時候就需要用到分佈式事務
也就是多文檔事務

首先看一個例子: 官網例子

# For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
# uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
# For a sharded cluster, connect to the mongos instances; e.g.
# uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
from pymongo import *


uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
client = MongoClient(uriString)
wc_majority = WriteConcern("majority", wtimeout=1000)

# Prereq: Create collections. CRUD operations in transactions must be on existing collections.
client.get_database(
    "mydb1", write_concern=wc_majority).foo.insert_one({'abc': 0})
client.get_database(
    "mydb2", write_concern=wc_majority).bar.insert_one({'xyz': 0})

# Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
def callback(session):
    collection_one = session.client.mydb1.foo
    collection_two = session.client.mydb2.bar

    # Important:: You must pass the session to the operations.
    collection_one.insert_one({'abc': 1}, session=session)
    collection_two.insert_one({'xyz': 999}, session=session)

# Step 2: Start a client session.
with client.start_session() as session:
    # Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
    session.with_transaction(
        callback, read_concern=ReadConcern('local'),
        write_concern=wc_majority,
        read_preference=ReadPreference.PRIMARY)

上面例子主要是展示了:

  1. 事務操作的集合要存在
  2. 事務操作要在同一個會話裏面

同時mongo分佈式事務還有以下特性:

  1. 事務提交之前,事務之內的數據改變對於其他操作不可見
  2. 對於多個shard上的事務,某一個shard上事務提交之後不需要等待其他分片事務提交,
    這一分片上事務內的數據更改可以對本地讀外部可見,
  3. 事務內的操作全部成功纔會提交,否則其他未生效數據更改將被丟棄

事務裏面操作的一些限制:

  1. 集合必須存在
  2. 不能操作特殊數據庫config、admin、local
  3. 不能操作sys數據庫下所有集合和固定集合
  4. 不能返回執行計劃
  5. 遊標操作需要在其事務範圍內

特別注意:建索引、創建集合等對集合本身的操作也不允許

總結來說: 就是事務內的操作不應涉及到集合的操作,包括因數據插入導致固定集合去刪除一部分內容, 只可以是增刪改查以及有限的獲取信息集合

額外:
isMaster, buildInfo, connectionStatus允許在事務中但不能在第一個操作

發佈了131 篇原創文章 · 獲贊 153 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章