多文档事务无法在 mongoDB 的分片集合中运行

问题描述 投票:0回答:1

我尝试将两个不同集合中的两个文档作为事务进行更新。但是每当我按照下面提到的文档中的建议运行交易时,我都会收到错误

Multi-document transactions cannot be run in a sharded collection in mongoDB

https://learn.microsoft.com/en-gb/azure/cosmos-db/mongodb/use-multi-document-transactions

是否有任何 mongodb 版本支持共享集合而不是固定集合上的多文档支持?

mongodb azure mongoose mongodb-query
1个回答
0
投票

多文档事务无法在 mongoDB 的分片集合中运行

如本文doc中所述,API 版本 4.0 中的非分片集合支持多文档事务。这就是错误发生的原因。在这个 Mongo DB API 版本 4.2 doc 中,明确提到了 仅在单个非分片集合中支持多文档事务。 因此,它不支持 Mongo 中具有分片键的多文档事务数据库 API 版本 4.2。

下面是 Mongo DB API 4.2 版本中支持使用单个非分片键集合进行多文档事务的代码。

const { MongoClient } = require('mongodb');

const uri = "mongodb://<username>:<password>@<username>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retryWrites=false";

const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        const db = client.db("users");

        await db.collection('friends').insertOne({ name: "Tom" });
        await db.collection('friends').insertOne({ name: "Mike" });

        const session = client.startSession();
        session.startTransaction();

        try {
            await db.collection('friends').updateOne({ name: "Tom" }, { $set: { friendOf: "Mike" } });
            
            await db.collection('friends').updateOne({ name: "Mike" }, { $set: { friendOf: "Tom" } });

            await session.commitTransaction();
        } catch (error) {
            await session.abortTransaction();
            throw error; 
        } finally {
            session.endSession();
        }
    } finally {
        await client.close();
    }
}

main().catch(console.error);

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.