I have tried running a insertMany/insertOne statement with transaction, but the mongo shell goes into a loading state indefinitely
Here's what I tried:
> use test;
> const session = db.getMongo().startSession();
> session.startTransaction();
> const doc = {name: "test", value: 1};
> db.myCollectionName.insertOne(doc, {session})
After this, it just stays on loading
Anyone can help me out ? I have a very specific usecase to use mongo shell only. I know this can be achieved very easily using Node/Py
You need to get the database from the session.
Mongosh is slightly different from node/py driver and uses shell helpers with their own syntax flavour.
https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/ accepts only writeConcern
options in the second parameter and ignores everything else.
Your session doesn't apply there, so it tries to write outside the transaction.
Use session.getDatabase()
instead:
use test;
const session = db.getMongo().startSession();
col = session.getDatabase(db.getName()).myCollectionName;
session.startTransaction();
const doc = {name: "test", value: 1};
col.insertOne(doc, {session})
session.commitTransaction();
session.endSession();
Now a word of warning - you learned from experience how an open transaction affects other operations. There is no workaround. They are just not designed to stay open for long time. Think again if you want to do it manually via shell.