If you run the below code, outside a transaction object will appear in the oplog as an insert operation but oplog will have no record of inside a transaction but they will be both saved properly to the collection.
I tried to look up the problem with no luck, although I was able to get a confirmation that in my mongodb server version, oplog will create a separate entry for each operation, although I don't get either the 4.0 style, nor the 4.2!
The Code
const { MongoClient } = require('mongodb');
const dbName = "db-name";
const collectionName = "collection-name";
const dbUri = "mongodb+srv://<user>:<pass>@<cluster-url>/<db-name>?retryWrites=true&w=majority";
const client = await new MongoClient(dbUri, { useUnifiedTopology: true }).connect();
const db = client.db(dbName);
const collection = db.collection(collectionName);
const session = client.startSession();
const transactionOptions = {
readConcern: { level: 'snapshot' },
writeConcern: { w: 'majority' }
};
await collection.insertOne({ name: "outside a transaction" });
await session.withTransaction(async () => {
await collection.insertOne({ name: "inside a transaction" }, { session: session});
}, transactionOptions);
await session.endSession();
await client.close();
Oplog Result
Query: db.oplog.rs.find({}).sort({$natural: -1})
Actual Count: 1
Expected Count: 2
{
"lsid":{
"id":{
"$binary":"IwdZfNnGTvGDoABb0gjxXQ==",
"$type":"4"
},
"uid":{
"$binary":"ddqot68vLpBUPnOuqFj2cdClv/dv/vF9ZVSwknYHEsE=",
"$type":"0"
}
},
"txnNumber":{
"$numberLong":"1"
},
"op":"i",
"ns":"testDb.tests",
"ui":{
"$binary":"2a1ZJWDySfGuvtgMK2G2gQ==",
"$type":"4"
},
"o":{
"_id":{
"$oid":"60f6feb12a662ec3fc985400"
},
"name":"outside a transaction"
},
"ts":{
"$timestamp":{
}
},
"t":{
"$numberLong":"73"
},
"wall":{
"$date":"2021-07-20T16:49:53.226Z"
},
"v":{
"$numberLong":"2"
},
"stmtId":0,
"prevOpTime":{
"ts":{
"$timestamp":{
}
},
"t":{
"$numberLong":"-1"
}
}
}
- Mongo Database Version: 4.2
- Mongo Database Setup: 3 Member Replica Set (Hosted on Atlas)
- Mongo Driver: Tried both V3.6 and V4 (both are compatible with the database version)
When I run this test on a MongoDB 5.0 (3-node replicaset) I see the two oplog entries...
use localdb.oplog.rs.find({ns: {$ne: ''}}).sort({ts: -1})Same thing in MongoDB 4.4....
MongoDB 4.2
MongoDB 4.0
Not testing with 3.6 since it is no longer a supported version and never supported transactions anyways.
I had to modify your example program to make it work, here is what I ran for a test...
Modified Test Program