Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading