Inserting a document in a transaction in MongoDB?

  • Within a transaction, a document is inserted.
  • Before the transaction is completed, will an outside query see this inserted document?

>Solution :


db.foo.drop();
db.createCollection("foo");

session = db.getMongo().startSession();

session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } );

fxx = session.getDatabase("testX").foo;

var n = 5;
for(var k = 0; k < n; k++) {
    fxx.insert(doc);
    print("check now");
    sleep(3000);
}

session.commitTransaction();

print("committed.  check now; you should now magically see " + k);

When you see "check now", call `db.foo.countDocuments() in ANOTHER mongosh. You will see 0 until the commit hits.

Leave a Reply