MongoDB Cheat-sheet

MongoDB Cheat-sheet

Create Database

use blog
db.createCollection("posts")

Connection string for replica set

mongodb://db1.server.com:port,db2.server.com:port,arbiter.server.com:port/MyDataBaseName?replicaSet=MyReplicaSetName

Connection string for an authenficated replica set

mongodb://myusername:mypassw0rd@db1.server.com:port,db2.server.com:port,arbiter.server.com:port/MyDataBaseName?replicaSet=MyReplicaSetName

Connection string for an authenficated replica set using 'admin' database to authenticate but connecting to another database

mongodb://myusername:mypassw0rd@db1.server.com:port,db2.server.com:port,arbiter.server.com:port/OtherBaseName?replicaSet=MyReplicaSetName&authSource=admin

Modify members of replica set

cfg = rs.conf()
cfg.members[0].host = "1.2.3.4:27017"
rs.reconfig(cfg)

runCommand() example

db.runCommand(
    { 
        update: "MyCollectionName", 
        updates: [
            { 
                q: { 
                    fieldNameToMatch: "ValueToMatch"
                }, 
                u: { 
                    $set: { 
                        fieldNameToUpdate: "ValueToSet"
                    }
                }, 
                upsert: false, 
                multi: false
            }
        ], 
        ordered: true
    }
);

updateOne() example

db.collection_name.updateOne(
    {
        _id: ObjectId("UUIDOFTHEOBJECT")
    } , {
        $set: {
            field1: {
                field2: "new value",
                field3: 3,
                field4: {
                    field5: false
                }
            }
        }
    }
);

Connect to authenticated replica set server from console

mongo mongodb://myusername:mypassword@localhost:27017/mydatabasename?replicaSet=rs0

Copy a collection to another database

use mydb1

db.perrosCollection.find().forEach(function (docs) { 
    db.getSiblingDB('mydb2').perrosCollection.insert(docs); 
})

List users

db.getUsers();

or

show users;

Dump server DBs into a GZip BSON archive file

/usr/bin/mongodump --gzip --archive=/var/backups/my_mongo_backup.bson.gz --uri="mongodb://mongo_admin:my_admin_passw0rd@server1:27017,server2:27017,server3:27017/?replicaSet=rs1&authSource=admin"

Restore a .bson backup file into a replicaset

/usr/bin/mongorestore --uri="mongodb://server-a:27017,server-b:27017,server-c:27017/?replicaSet=rs1" --nsInclude=db_name.collectionName --nsInclude=dn_name.collection.name --archive=my-mongodb-backup.bson

find() example

use MyDataBaseName
db.getCollection('MyCollectionName').find({}).toArray()