I'm trying to test some update / delete scripts against a localhost MongoDB server (which is a docker instance).
eg.
update all users, set age = 50
delete all users where eyes = blue
select all users
If I was to do this with SQL, I would wrap the those three queries inside a TRANSACTION.
So I had a look online to doing transactions with MongoDB and it feels like it's a PITA -> I need a REPLICA SET, etc.
Is there a really easy way to:
- create a mongodb instance with docker
- write a script (like above) inside a transaction, and run this against that docker instance?
My reasoning for using a transaction is so i can change the data, get the current version of the data (after the change) .. eye ball the results ... and then roll back (revert) those changes. Then keep iterating through my script until I'm happy.
Here's some stuff I was trying to prove my point:
docker-compose.yml
version: '3.5'
services:
mongodb.data:
container_name: mongodb.data
image: mongo
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=example
volumes:
- ./:/usr/src/mongo-data
and some mongo shell script I'm playing around with in Studio 3T:
// Start a session.
session = db.getMongo().startSession( { readPreference: { mode: "primary" } } );
// Start a transaction
session.startTransaction( { readConcern: { level: "local" }, writeConcern: { w: "majority" } } );
usersCollection = session.getDatabase("users").users;
usersCollection.find(
{
"_id.userId" : "abcde1234"
}
);
usersCollection.update(
{ "_id.userId" : "abcde1234" },
{
$set: {
tags: Date()
}
},
{ multi:true }
);
session.abortTransaction();
//session.commitTransaction();
session.endSession();
and the error I get when I try to use a transaction:
WriteCommandError({
"ok" : 0,
"errmsg" : "Transaction numbers are only allowed on a replica set member or mongos",
"code" : 20,
"codeName" : "IllegalOperation"
})
Is this even possible with a simple MongoDB setup?