Transaction support isn’t available in MongoDB 4.0. To get similar results, use findOneAndUpdate().
Let us create a collection with documents −
> db.demo404.insertOne({"FirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f8c38fac4d418a0178592") } > db.demo404.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f8c3cfac4d418a0178593") } > db.demo404.insertOne({"FirstName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f8c40fac4d418a0178594") }
Display all documents from a collection with the help of find() method −
> db.demo404.find();
This will produce the following output −
{ "_id" : ObjectId("5e6f8c38fac4d418a0178592"), "FirstName" : "John" } { "_id" : ObjectId("5e6f8c3cfac4d418a0178593"), "FirstName" : "Robert" } { "_id" : ObjectId("5e6f8c40fac4d418a0178594"), "FirstName" : "Mike" }
Following is the query to use findOneAndUpdate and set lock in MongoDB −
> result=db.demo404.findOneAndUpdate({"in_transaction": {"$exists": false}}, {"$set": {"in_transaction": true}});
This will produce the following output −
{ "_id" : ObjectId("5e6f8c38fac4d418a0178592"), "FirstName" : "John" }