This article talks about the frequently used queries and commands of MongoDB used by developers and DBA in their day to day development and operation life.
Quick Intro
In this new era of smart technology, data is being generated in high volume and every piece of data is equally important for growing industries. Users are generating structured, semi-structured, and unstructured data in an unlimited amount. Structured Data comprises storing data in tables and rows whereas unstructured data consists of images, videos, and voice clips. Due to increasing data volume of structured and unstructured Data necessity of NoSQL Database comes into the picture.
It provides developers ease of designing schema and scalable platform to database administrators, it provides a secure and speedy platform.
What is MongoDB?
MongoDB is a document-oriented, cross-platform and open-source NoSQL Database used to store semi-structured data written in C++. Instead of tables and rows, MongoDB stores data in key-value pairs. To make learning easy and hustle free for developers and administrators, here are some of the frequently used MongoDB commands.
Let’s get it started.
Basic Commands
1. Version check
The foremost command is to check the installed version of the MongoDB server and Mongo Shell. Run this command on the terminal on Linux or CMD prompt on windows.
mongod --version
C:\Windows\System32>mongod --version
db version v4.2.7
git version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
allocator: tcmalloc
modules: none
build environment:
distmod: 2012plus
distarch: x86_64
target_arch: x86_64
We can also use mongod
command to check the version, as follows.
mongo –version
C:\Windows\System32>mongo --version
MongoDB shell version v4.2.7
git version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
allocator: tcmalloc
modules: none
build environment:
distmod: 2012plus
distarch: x86_64
target_arch: x86_64
2. Listing MongoDB commands
This command will help users to find out all the commands which can be used in MongoDB. Run the command on Mongo Shell.
help()
mongo> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
db.createCollection(name, {size: ..., capped: ..., max: ...})
db.createUser(userDocument)
db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
db.currentOp() displays currently executing operations in the db
db.dropDatabase(writeConcern)
db.dropUser(username)
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.getName()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
db.shutdownServer()
db.stats()
db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
db.version() current version of the server
db.watch() - opens a change stream cursor for a database to report on all changes to its non-system collections.
3. DB statistics
The below command will give details of databases along with several collections and related parameters of that Database.
db.stats()
> db.stats()
{
"db" : "test",
"collections" : 0,
"views" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"scaleFactor" : 1,
"fileSize" : 0,
"fsUsedSize" : 0,
"fsTotalSize" : 0,
"ok" : 1
}
4. Create New DB or Switch to Existing DB
This simple command help to create a new database if it doesn’t exist or help to switch to the existing Database. In MongoDB “test” is default database hence users use “test” DB once Mongo Shell is logged in.
use DB_Name
mongos> use geekFlareDB
switched to db geekFlareDB
5. Listing all the Databases
The mentioned command is being used to list all the databases.
show dbs
mongo> show dbs
admin 0.000GB
config 0.002GB
geekFlareDB 0.000GB
test 0.000GB
6. Check the DB currently in use
Run below command on Mongo Shell to see the DB currently in use.
db
> db
GeekFlare
7. Drop Database
The given command helps the user to drop the required database. Run the command on MongoDB client. Please make sure to select the Database before running the drop command. Otherwise, it will drop the default “test” Database.
db.dropDatabase()
Let’s first list out all the database, switch to one of them and then drop it
> show dbs
admin 0.000GB
config 0.001GB
local 0.000GB
test 0.000GB
training 0.000GB
>
> use training
switched to db training
>
> db.dropDatabase()
{ "dropped" : "training", "ok" : 1 }
8. Create Collection
Collections are similar to tables in RDBMS.
Create a collection command consists of two parameters. The collection consists of zero or more documents. Hence for creating a collection mandatory parameter to use in command is its name and optional parameter might include the name of documents, its size, and index.
- Creating a simple collection.
Syntax: db.createCollection(Name,Options)
Example:
> use geekFlare
switched to db geekFlare
>
> db.createCollection("geekFlareCollection")
{ "ok" : 1 }
>
> show collections
geekFlareCollection
- Creating a Capped Collection
In this, restrict the size and number of the documents to be inserted into the collection. The capped collection has a property to remove the oldest documents to make space for new documents.
Syntax:
db.createCollection(Name,{capped : true, size : sizeLimit , max : documentLimit })
Example: Let’s create a capped collection, insert a record and retrieve it
> db.createCollection("Login",{capped:true,max:1,size:200})
{ "ok" : 1 }
>
> db.Login.insertMany([{"id":1,status:"Active"},{"id":2,status:"Hold"},{"id":3,status:"Pending"}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5edc5f4f411247725e75e52e"),
ObjectId("5edc5f4f411247725e75e52f"),
ObjectId("5edc5f4f411247725e75e530")
]
}
>
> db.Login.find()
{ "_id" : ObjectId("5edc5f4f411247725e75e530"), "id" : 3, "status" : "Pending" }
9. Drop Collection
Drop Collection command is similar to DDL in RDBMS. It acquires locks on the required collection until the execution of the command. Drop collection removes the collection from the DB along with all the indexes associated with that collection. To drop the collection drop() method is required.
It returns true for successful drop and false in case of any error or if DB doesn’t exist.
Syntax: collectionName.drop()
Example:
> use geekFlare
switched to db geekFlare
>
> show collections
geekFlareCollection
>
> db.geekFlareCollection.drop()
true
>
> db.geekFlareCollection.drop()
false
10. Insert Document into Collection
In MongoDB document is similar to a tuple in RDBMS.
To create a document, the insert()
method is used. The insert() method creates one or many documents in the existing collection. It also creates collection if it is not present in DB. In MongoDB, Document is schema-less, it means there is no restriction in inserting any number of keys in a document.
- Inserting a single record
To insert one record insert()
or insertOne()
method can be used.
Syntax: collectionName.insertOne({document})
Example:
> db.geekFlareCollection.insertOne( {
code: "P123", Qty: 200, status: "Active"
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ed309725429283aee2e134d")
}
- Inserting multiple records
To insert many records, a list of records will be passed to insert()
or insertMany()
method.
Syntax:
collectionName.insertMany([{document1},{document2},{ document3}….{ documentn}])
Example:
db.geekFlareCollection.insertMany([
... { code: "P1", Qty: 100, status: "Active"},
... { code: "P2", Qty: 200, status: "Active"},
... { code: "P3", Qty: 0, status: "Dective"}
... ]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5edf7b4e18b2c26b9dfe8cac"),
ObjectId("5edf7b4e18b2c26b9dfe8cad"),
ObjectId("5edf7b4e18b2c26b9dfe8cae")
]
}
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75b8"), "product" : "bottles", "Qty" : 100 }
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75b9"), "product" : "bread", "Qty" : 20 }
{ "_id" : ObjectId("5edf546fdfa12b33b7cb75ba"), "product" : "yogurt", "Qty" : 30 }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cac"), "code" : "P1", "Qty" : 100, "status" : "Active" }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cad"), "code" : "P2", "Qty" : 200, "status" : "Active" }
{ "_id" : ObjectId("5edf7b4e18b2c26b9dfe8cae"), "code" : "P3", "Qty" : 0, "status" : "Dective" }
>
- Inserting record in bulk
A huge number of documents can also be inserted in an ordered and unordered manner by executing initializeOrderedBulkOp()
and initializeUnorderedBulkOp()
methods.
Syntax:
var bulk = db.collectionName.initializeUnorderedBulkOp();
bulk.insert({document1} );
bulk.insert({document2} );
bulk.insert({documentn} );
bulk.execute();
Example:
> var bulk = db.geekFlareCollection.initializeUnorderedBulkOp();
> bulk.insert({ code: "P1", Qty: 100, status: "Active"});
> bulk.insert({ code: "P2", Qty: 200, status: "Active"});
> bulk.insert({ code: "P3", Qty: 0, status: "Dective"});
> bulk.execute();
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf7be318b2c26b9dfe8caf"), "code" : "P1", "Qty" : 100, "status" : "Active" }
{ "_id" : ObjectId("5edf7be318b2c26b9dfe8cb0"), "code" : "P2", "Qty" : 200, "status" : "Active" }
{ "_id" : ObjectId("5edf7be318b2c26b9dfe8cb1"), "code" : "P3", "Qty" : 0, "status" : "Dective" }
>
11. Retrieve Document from a Collection
To search for the document stored in a collection find() method can be used. The below command will be used to retrieve all the documents from the collection.
find()
method can be used to retrieve all documents stored in a collection.
Syntax: collectionName.find()
Example:
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86ce"), "code" : "P1", "Qty" : 200, "status" : "Active" }
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86cf"), "code" : "P2", "Qty" : 200, "status" : "Active" }
{ "_id" : ObjectId("5ed31186b6f2c2bb1edb86d0"), "code" : "P3", "Qty" : 200, "status" : "Active" }
{ "_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"), "code" : "P4", "Qty" : 100, "status" : "Inactive" }
find({condition})
method can be used to retrieve only the required documents based on some conditions from the collection. MongoDB provides a list of projection and Query operators to retrieve BSON type value.
Syntax: collectionName.find({ condition })
Example:
> db.geekFlareCollection.find({ Qty: { $eq: 100 }});
{ "_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"), "code" : "P4", "Qty" : 100, "status" : "Inactive" }
- To retrieve only one document MongoDB provides the
findOne
() method. It gives a formatted output.
Syntax: collectionName.findOne()
Example:
> db.geekFlareCollection.findOne();
{
"_id" : ObjectId("5ed31186b6f2c2bb1edb86ce"),
"code" : "P1",
"Qty" : 200,
"status" : "Inactive"
}
12. Beautify Retrieval output
The find()
method gives a disorganized output. MongoDB provides pretty()
commands to get the formatted output.
Syntax: collectionName.find().pretty()
Example:
> db.geekFlareCollection.find({ Qty: { $eq: 100 }}).pretty();
{
"_id" : ObjectId("5ed3159eb6f2c2bb1edb86d1"),
"code" : "P4",
"Qty" : 100,
"status" : "Inactive"
}
13. Update Document in a Collection
MongoDB provides update()
method to set new values for existing keys in documents. Update command gives details of modified and matched documents. Syntax of update command is:
Syntax: collectionName.update({KeyToUpdate},{Set Command})
Example:
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" : "bottles", "Qty" : 100 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread", "Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" : "yogurt", "Qty" : 30 }
>
> db.geekFlareCollection.update({"product" : "bottles"},{$set : {"Qty": 10}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" : "bottles", "Qty" : 10 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread", "Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" : "yogurt", "Qty" : 30 }
>
> db.geekFlareCollection.find()
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfb"), "product" : "bottles", "Qty" : 10 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfc"), "product" : "bread", "Qty" : 20 }
{ "_id" : ObjectId("5edf3f67d6bfbd8125f58cfd"), "product" : "yogurt", "Qty" : 30 }
updateOne()
: To update a single document there isupdateOne()
method.updateOne()
give the count of matched and modified documents.
Syntax: collectionName.updateOne({SingleKeyToUpdate},{Set Command})
Example:
> db.geekFlareCollection.updateOne({"product" : "bottles"},{$set : {"Qty": 40}} )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
<strong>updateMany()</strong>
: To update multiple documents on some condition MongoDB hasupdateMany()
method.
Syntax: collectionName.updateMany({filter},{Set Command})
Example:
> db.geekFlareCollection.updateMany( { "Qty" : { $lt: 30 } },{ $set: { "Qty": "Inactive"} } )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
14. Delete Document of a Collection
To delete the document, MongoDB consist of deleteOne()
and deleteMany()
methods. Syntax of delete methods are:
<strong>deleteOne({condition}) </strong>
removes the single document meeting the deletion criteria.
Syntax: collectionName.deleteOne({DeletionCondition})
Example:
> db.geekFlareCollection.deleteOne({"product" : "bread"})
{ "acknowledged" : true, "deletedCount" : 1 }
<strong>deleteMany() </strong>
removes all the documents matching the deletion criteria. Without the deletion criteriadeleteMany({condition})
removes all the documents.
Syntax: collectionName.deleteMany({DeletionCondition})
Example:
> db.geekFlareCollection.deleteMany({"product" : "bottles"})
{ "acknowledged" : true, "deletedCount" : 2 }
<strong>remove() </strong>
There is another method to delete all the documents matching the deletion criteria. remove() method takes two arguments, one is deletion condition and the other is just one flag.
Note: Remove method is deprecated in upcoming versions.
Syntax: collectionName.remove({DeletionCondition},1)
Example:
> db.geekFlareCollection.remove({"product" : "bottles"})
WriteResult({ "nRemoved" : 1 })
15. Retrieve Distinct
The distinct()
method is used to get unique records.
- To get distinct records from one field.
Syntax: collectionName.distinct(field)
Example:
> db.geekFlareCollection.distinct("product")
[ "Cheese", "Snacks2", "Snacks3", "bread", "ketchup" ]
- To get distinct records from one field while specifying the query.
Syntax: collectionName.distinct(field,query)
Example:
> db.geekFlareCollection.distinct('product',{"Qty":20})
[ "Snacks3", "bread" ]
16. Rename collection
MongoDB provides renameCollection ()
method to rename collection.
Syntax: collectionName.renameCollection(newCollectionName)
Example:
>db.geekFlareCollection.renameCollection('geekFlareCol')
{ "ok" : 1 }
> show collections
geekFlareCol
Indexing
17. Create Index on Document
Indexes are a special data structure that stores a small part of the collection’s data set in easy to traverse form. Indexes support ascending and descending ordering of fields values and hence facilitate better performance while retrieval.
MongoDB provides the default_id
index. Also, MongoDB supports the creation of user-defined Indexes. MongoDB indexes are defined at collections level and it provides supports at field or sub-field of a document. Syntax of create the index is :
- Create an index on a single field.
Syntax: collectionName.createIndex({Key:1})
In this, the key indicates the field on which index is created and 1 signifies ascending order. To create an index in descending order -1 can be used.
Example:
> db.geekFlareCollection.createIndex({"product" : 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
- Create an index on multiple fields.
Syntax: collectionName.createIndex({Key1:1,key2:1…keyn:1})
Example:
> db.geekFlareCollection.createIndex({"product" : 1,"Qty":-1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
18. Show Index on Document
MongoDB provides getIndexes()
method to list all the indexes created on a document.
Syntax: collectionName.getIndexes()
Example:
> db.geekFlareCollection.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "geekFlareCollection.geekFlareCollection"
}
]
19. Remove Index from Document
dropIndex()
method is used to drop the single index and dropIndexes() method is used to delete multiple indexes.
- Remove Single Index
Syntax: collectionName.dropIndex({key})
Example:
> db.geekFlareCollection.dropIndex({"product" : 1})
{ "nIndexesWas" : 3, "ok" : 1 }
- Remove Multiple Indexes.
Syntax: collectionName.dropIndexes({key1,key2…,keyN})
Example:
> db.geekFlareCollection.dropIndexes({"product" : 1,"Qty":-1})
{ "nIndexesWas" : 3, "ok" : 1 }
20. Limit retrieval of documents
limit()
method helps to limit the number of documents returned. The limit() method accepts numerical arguments.
Syntax: collectionName.find().limit(number)
Example:
> db.geekFlareCollection.find().limit(2)
{ "_id" : ObjectId("5ed3c9e7b6f2c2bb1edb8702"), "product" : "bottles", "Qty" : 100 }
{ "_id" : ObjectId("5ed3c9e7b6f2c2bb1edb8703"), "product" : "bread", "Qty" : 20 }
21. Skip retrieval of documents
MongoDB supports skip()
method. This method skips the required number of documents. It accepts a numeric argument.
Syntax: collectionName.find().skip(number)
Example:
> db.geekFlareCollection.find().skip(2)
{ "_id" : 3, "product" : "yogurt", "Qty" : 30 }
> db.geekFlareCollection.find().skip(3)
22. Sort retrieval of documents
MongoDB sort()
method sort the output documents either in ascending or descending order. This method accepts the name of keys with the number to specify sorting order 1 is used for ascending order whereas -1 is used to specify descending order.
Syntax: collectionName.find().sort({key:1})
Example:
> db.geekFlareCollection.find().sort({"Qty":1})
{ "_id" : 2, "product" : "bread", "Qty" : 20 }
{ "_id" : 3, "product" : "yogurt", "Qty" : 30 }
{ "_id" : 1, "product" : "bottles", "Qty" : 100 }
23. Document validation
Validators help to restrict the type of data being inserted in the documents. Validators are defined on collection. Validator creation is required to use keyword validator and optional validation level and validation action to specify the validation mode. Document validation doesn’t restrict the insertion of the new field in the document.
Syntax: createCollection(“collectionName”,{validator:{ fields condition }})
Example:
> db.createCollection( "Login",
... { validator: { $and:
... [
... { phone: { $type: "string" } },
... { email: { $regex: /@flares\.com$/ } },
... { status: { $in: [ "Registered", "Unknown" ] } }
... ]
... }
... } )
{ "ok" : 1 }
>
> db.Login.insert({phone:1234})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
>
> db.Login.insert({phone:"1234",email:"abc@flares.com",status:"Unknown",mode:"limited"})
WriteResult({ "nInserted" : 1 })
24. Schema Validators on a new collection
Additional keyword $jsonSchema along with additional properties value as False is required to put restriction at the schema level. It prevents new fields to be added in the document.
Syntax: createCollection(“collectionName”,{validator: { $jsonSchema { schema condition } }})
Example:
> db.createCollection( "Login", {
... validator: { $jsonSchema: {
... bsonType: "object",
... "additionalProperties": false,
... required: [ "email" ],
... properties: {
... email: {
... bsonType : "string",
... pattern : "@flares\.com$",
... description: "string meets the given expression"
... },
... status: {
... enum: [ "registered", "Invalid" ],
... description: "status must be within enum values"
... }
... }
... } },
... } )
{ "ok" : 1 }
>
> db.Login.insert({email:"abc@flares.com"})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
25. Update or Create Schema Validators on an existing collection
A validator can be created on existing collection using collMod
Syntax: runCommand({collMod:”collectionName”,validator:{schema condition}})
Example:
> db.runCommand( {
collMod: "Login",
validator: { $jsonSchema: {
bsonType: "object",
"additionalProperties": false,
required: [ "email","status" ],
properties: {
email: {
bsonType : "string",
pattern : "@flares\.com$",
description: "string meets the given expression"
},
status: {
enum: [ "registered", "Invalid" ],
description: "status must be within enum values"
}
}
} },
validationAction: "error",
validationLevel: "strict"
} )
{ "ok" : 1 }
26. Remove Schema Validators on an existing collection
For removing schema validators it requires to set <strong>validationLevel</strong>
as off.
Syntax: runCommand({collMod:”collectionName”,validator:{ },validationLevel:off})
Example:
> db.runCommand({
collMod:"Login",
validator:{},
validationLevel:"off"
})
{ "ok" : 1 }
>
> db.Login.insert({"email":"abc"})
WriteResult({ "nInserted" : 1 })
27. Check for Validators on an existing collection
To check if the existing collection is having schema validators run below command. Without specifying the collection name db.getCollectionInfos()
method gives details of validators on all collections residing inside a DB.
Syntax: getCollectionInfos({name : “collectionName”})
Example:
> db.getCollectionInfos({name: "Login"})
[
{
"name" : "Login",
"type" : "collection",
"options" : {
"validator" : {
"email" : {
"$regex" : /@flares\.com$/
}
}
},
"info" : {
"readOnly" : false,
"uuid" : UUID("646674f6-4b06-466d-93b0-393b5f5cb4ff")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "geekFlareDB.Login"
}
}
]
28. Cursor in MongoDB
The cursor is a pointer to iterate over the result set. MongoDB uses <strong>hasNext()</strong>
and <strong>forEach()</strong>
method for iteration. A list of cursor methods has been provided.
Examples:
> var newCursor=db.geekFlareCollection.find() > newCursor.forEach(printjson) { "_id" : 1, "product" : "bottles", "Qty" : 100 } { "_id" : 2, "product" : "bread", "Qty" : 20 } { "_id" : 3, "product" : "yogurt", "Qty" : 30 } > > var newCursor1=db.geekFlareCollection.find() > while(newCursor1.hasNext()){ printjson(newCursor1.next())} { "_id" : 1, "product" : "bottles", "Qty" : 100 } { "_id" : 2, "product" : "bread", "Qty" : 20 } { "_id" : 3, "product" : "yogurt", "Qty" : 30
Utility
29. Taking a database backup
mongodump
utility is used to export the content of the MongoDB database as a backup. This command runs from system console and not from mongo shell. It will generate binary backup along with metadata information.
Syntax:
mongodump --db dbName --out outFile --host "IP:PORT" --username <user> --password <pass>
Example:
C:\mongodb\dump>mongodump --db geekFlareDB --out "C:\mongodb\dump" --host "127.0.0.1:27017"
2020-06-02T12:26:34.428+0530 writing geekFlareDB.myTable to
2020-06-02T12:26:34.430+0530 writing geekFlareDB.geekFlareCollection to
2020-06-02T12:26:34.430+0530 writing geekFlareDB.mCollection to
2020-06-02T12:26:34.433+0530 writing geekFlareDB.users to
2020-06-02T12:26:34.434+0530 done dumping geekFlareDB.myTable (2 documents)
2020-06-02T12:26:34.434+0530 done dumping geekFlareDB.geekFlareCollection (4 documents)
2020-06-02T12:26:34.435+0530 writing geekFlareDB.contacts2 to
2020-06-02T12:26:34.435+0530 writing geekFlareDB.Login to
2020-06-02T12:26:34.436+0530 done dumping geekFlareDB.mCollection (2 documents)
2020-06-02T12:26:34.437+0530 done dumping geekFlareDB.users (1 document)
2020-06-02T12:26:34.437+0530 done dumping geekFlareDB.Login (0 documents)
2020-06-02T12:26:34.438+0530 done dumping geekFlareDB.contacts2 (0 documents)
30. Restoring database from Backup
The utility <strong>mongorestore</strong>
is used to restore binary data generated by mongodump
.
Syntax: mongorestore --db newDB "pathOfOldBackup"
Example:
C:\Users\asad.ali>mongorestore --db geekFlareNew "C:\mongodb\dump\geekFlare" --host "127.0.0.1:27017"
2020-06-09T15:49:35.147+0530 the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
2020-06-09T15:49:35.148+0530 building a list of collections to restore from C:\mongodb\dump\geekFlare dir
2020-06-09T15:49:35.152+0530 reading metadata for geekFlareNew.geekFlareCollection from C:\mongodb\dump\geekFlare\geekFlareCollection.metadata.json
2020-06-09T15:49:35.321+0530 restoring geekFlareNew.geekFlareCollection from C:\mongodb\dump\geekFlare\geekFlareCollection.bson
2020-06-09T15:49:35.461+0530 no indexes to restore
2020-06-09T15:49:35.462+0530 finished restoring geekFlareNew.geekFlareCollection (3 documents, 0 failures)
2020-06-09T15:49:35.467+0530 3 document(s) restored successfully. 0 document(s) failed to restore.
31. Exporting collections
To export content of collection to a file (JSON or CSV) mongoexport
utility has been provided. To run this command use system terminal.
- Export a single collection to a file.
Syntax: mongoexport --db dbName --collection collectionName --out outputFile
Example:
C:\mongodb\New folder>mongoexport --db geekFlareDB --collection geekFlareCol --out outFile.json
2020-06-06T19:02:29.994+0530 connected to: mongodb://localhost/
2020-06-06T19:02:30.004+0530 exported 6 records
- Export a specific field from collection to a file.
Syntax: mongoexport --db dbName --collection collectionName --out outputFile --fields fieldname
Example:
C:\mongodb\New folder>mongoexport --db geekFlareDB --collection geekFlareCol --out outFile.json --fields product
2020-06-06T19:05:22.994+0530 connected to: mongodb://localhost/
2020-06-06T19:05:23.004+0530 exported 6 records
32. Importing collections
To import data from file (CSV or JSON) mongoimport
command-line tool can be used.
Syntax: mongoimport --db dbName --collection collectionName --file inputFile
C:\Users\asad.ali>mongoimport --db geekFlareDB --collection geekFlareNew --file outFile.json
2020-06-09T14:52:53.655+0530 connected to: mongodb://localhost/
2020-06-09T14:52:53.924+0530 6 document(s) imported successfully. 0 document(s) failed to import.
Replication is different than sharding, check out this guide to implement Sharding.
33. MongoDB Replication
Replication is the process to synchronize data on multiple servers. It prevents data loss due to hardware or software malfunctioning. MongoDB achieves replication using Replica sets. The replica set consists of Primary and secondary Mongo data sets in the cluster.
Primary Data set accepts all write operations and secondary data set reads from Primary. Minimum 3 data sets are required in Mongo Replica set. Below process is required to set up a replica set:
- Start
mongod
server withreplset
option on a minimum of 3 nodes.
mongod --port 27017 --dbpath C:\data\data1 --replSet rs0 --oplogSize 128
mongod --port 27018 --dbpath C:\data\data1 --replSet rs0 --oplogSize 128
mongod --port 27019 --dbpath C:\data\data1 --replSet rs0 --oplogSize 128
- Initialize the replica set.
rs.initiate( { _id : "rs0", members: [ { _id: 0, host: "IP:27017" }, { _id: 1, host: "IP:27018" }, { _id: 2, host: "IP:27019" } ] })
> rs.initiate( {
... _id : "rs0",
... members: [
... { _id: 0, host: "localhost:27017" },
... { _id: 1, host: "localhost:27018" },
... { _id: 2, host: "localhost:27019" }
... ]
... })
{
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1591089166, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1591089166, 1)
}
34. Check the status of Replication
Run below command from the primary replica node to get complete info of the replica set.
rs.conf()
rs.status()
rs0:PRIMARY> rs.conf()
{
"_id" : "rs0",
"version" : 2,
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"members" : [
{
"_id" : 0,
"host" : "localhost:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "localhost:27018",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "localhost:27019",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
},
{
"_id" : 3,
"host" : "localhost:27016",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"slaveDelay" : NumberLong(0),
"votes" : 1
}
],
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("5ed6180d01a39f2162335de5")
}
}
35. Add new MongoDB instance to a replica set
Start Primary MongoDB client and run below command
Syntax: rs.add(“hostname:port”)
Example:
rs0:PRIMARY> rs.add("localhost:27016")
{
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1591094195, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1591094195, 1)
}
36. Remove existing MongoDB instance from the replica set
The below command will remove the required secondary host from the replica set.
Syntax: rs.remove("localhost:27017")
Example:
rs0:PRIMARY> rs.remove("localhost:27016")
{
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1591095681, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1591095681, 1)
}
rs0:PRIMARY>
37. Make Primary as Secondary replica set
MongoDB provides a command to instruct primary replica to become a secondary replica set.
Syntax: rs.stepDown( stepDownSecs , secondaryCatchupSecs )
Example:
rs0:PRIMARY> rs.stepDown(12)
{
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1591096055, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1591096055, 1)
}
rs0:SECONDARY>
38. Check the Replica Lag between primary and Secondary
The below command will be used to check the replication lag between all replica set from the primary.
Syntax: rs.printSlaveReplicationInfo()
Example:
rs0:PRIMARY> rs.printSlaveReplicationInfo()
source: localhost:27018
syncedTo: Tue Jun 02 2020 16:14:04 GMT+0530 (India Standard Time)
0 secs (0 hrs) behind the primary
source: localhost:27019
syncedTo: Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
1591094644 secs (441970.73 hrs) behind the primary
source: localhost:27016
syncedTo: Tue Jun 02 2020 16:14:04 GMT+0530 (India Standard Time)
0 secs (0 hrs) behind the primary
rs0:PRIMARY>
39. Transactions in MongoDB
MongoDB supports ACID properties for transactions on documents.
To start a transaction, a session is required to start, and commit is required to save changes to the database. Transactions are supported on replica set or mangos. Once the session committed successfully, operations made inside the session will be visible outside.
- Start session
Syntax: session =
db.getMongo().startSession()
- Start transaction,
Syntax: session.startTransaction()
- Commit transaction
Syntax: session.commitTransaction()
Example:
Let’s create a session, start the transaction, perform some insert/update and then commit the transaction.
rs0:PRIMARY> session = db.getMongo().startSession()
session { "id" : UUID("f255a40d-81bd-49e7-b96c-9f1083cb4a29") }
rs0:PRIMARY> session.startTransaction()
rs0:PRIMARY> session.getDatabase("geekFlareDB").geekFlareCollection.insert([
... {_id: 4 , product: "ketchup"},
... {_id: 5, product: "Cheese"}
... ]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
rs0:PRIMARY> session.getDatabase("geekFlareDB").geekFlareCollection.find()
{ "_id" : 1, "product" : "bread", "Qty" : 20 }
{ "_id" : 2, "product" : "bottles", "Qty" : 100 }
{ "_id" : 3, "product" : "bread", "Qty" : 20 }
{ "_id" : 4, "product" : "ketchup" }
{ "_id" : 5, "product" : "Cheese" }
rs0:PRIMARY> db.geekFlareCollection.find()
{ "_id" : 1, "product" : "bread", "Qty" : 20 }
{ "_id" : 2, "product" : "bottles", "Qty" : 100 }
{ "_id" : 3, "product" : "bread", "Qty" : 20 }
rs0:PRIMARY> session.commitTransaction()
rs0:PRIMARY> db.geekFlareCollection.find()
{ "_id" : 1, "product" : "bread", "Qty" : 20 }
{ "_id" : 2, "product" : "bottles", "Qty" : 100 }
{ "_id" : 3, "product" : "bread", "Qty" : 20 }
{ "_id" : 4, "product" : "ketchup" }
{ "_id" : 5, "product" : "Cheese" }
rs0:PRIMARY> session.getDatabase("geekFlareDB").geekFlareCollection.find()
{ "_id" : 1, "product" : "bread", "Qty" : 20 }
{ "_id" : 2, "product" : "bottles", "Qty" : 100 }
{ "_id" : 3, "product" : "bread", "Qty" : 20 }
{ "_id" : 4, "product" : "ketchup" }
{ "_id" : 5, "product" : "Cheese" }
40. Single Document Transactions Conflict
If two transactions tried to update the same document, MongoDB throws write conflict error.
session1.startTransaction()
session2.startTransaction()
Perform some insert/update on Session1 followed by on Session2. Now observe the error in the below example
Example:
rs0:PRIMARY> session1.startTransaction()
rs0:PRIMARY> session2.startTransaction()
rs0:PRIMARY> session1.getDatabase("geekFlareDB").geekFlareCollection.update({_id:3},{$set:{ product: "Bread" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
rs0:PRIMARY> session2.getDatabase("geekFlareDB").geekFlareCollection.update({_id:3},{$set:{ product: "Snacks" }})
WriteCommandError({
"errorLabels" : [
"TransientTransactionError"
],
"operationTime" : Timestamp(1591174593, 1),
"ok" : 0,
"errmsg" : "WriteConflict",
"code" : 112,
"codeName" : "WriteConflict",
"$clusterTime" : {
"clusterTime" : Timestamp(1591174593, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
})
rs0:PRIMARY>
41. Multi-Document Transactions
MongoDB support multi-document transactions in a single session.
- db.getMongo().startTransaction()
Perform some insert/update on multiple documents
- session.commitTransaction()
Example:
rs0:PRIMARY> var session = db.getMongo().startSession()
rs0:PRIMARY> session.startTransaction()
rs0:PRIMARY> session.getDatabase("geekFlareDB").geekFlareCollection.update({_id:3},{$set:{ product: "Snacks3" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
rs0:PRIMARY> session.getDatabase("geekFlareDB").geekFlareCollection.update({_id:2},{$set:{ product: "Snacks2" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
rs0:PRIMARY> session.commitTransaction()
rs0:PRIMARY> db.geekFlareCollection.find()
{ "_id" : 1, "product" : "bread", "Qty" : 20 }
{ "_id" : 2, "product" : "Snacks2", "Qty" : 100 }
{ "_id" : 3, "product" : "Snacks3", "Qty" : 20 }
{ "_id" : 4, "product" : "ketchup" }
{ "_id" : 5, "product" : "Cheese" }
rs0:PRIMARY>
42. Profiling in MongoDB
Profiling helps in logging slow queries in the system.profile
collection. Profiler level and sample rate define the percentage of queries to be logged in system.profile
collection.
- Set/Get Profiling level
Syntax:
db.setProfilingLevel(profilingLevel,{"slowms":time,"sampleRate":LoggingPercentage})
> db.setProfilingLevel(2,{"slowms":1,"sampleRate":1})
{ "was" : 1, "slowms" : 1, "sampleRate" : 0.5, "ok" : 1 }
>
> db.getProfilingLevel()
2
- Get Profiling Status
Syntax: db.getProfilingStatus()
> db.getProfilingStatus()
{ "was" : 2, "slowms" : 1, "sampleRate" : 1 }
- To enable profiling at MongoDB instance level, start the instance with profiler information or add profiler details in the configuration file.
Syntax:
mongod --profile <Level> --slowms <time> --slowOpSampleRate <%Logging>
Example:
C:\Windows\System32>mongod --port 27017 --dbpath C:\data\data1 --profile 1 --slowms 25 --slowOpSampleRate 0.5
2020-06-09T02:34:41.110-0700 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-06-09T02:34:41.113-0700 W ASIO [main] No TransportLayer configured during NetworkInterface startup
2020-06-09T02:34:41.113-0700 I CONTROL [initandlisten] MongoDB starting : pid=22604 port=27017 dbpath=C:\data\data1 64-bit host=MCGL-4499
2020-06-09T02:34:41.114-0700 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2020-06-09T02:34:41.116-0700 I CONTROL [initandlisten] db version v4.2.7
2020-06-09T02:34:41.116-0700 I CONTROL [initandlisten] git version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
43. MongoDB Explain()
MongoDB explains()
method returns statistics and provides information to select a winning plan and execute it to completion. It returns results as per the verbosity plan.
Syntax: collectionName.explain(“verbosityName”)
To execute explain() method/command, let’s create a verbosity and then execute explain() method, have a look at the below example, where these steps have been executed.
Example:
> db.runCommand(
... {
... explain: { count: "product", query: { Qty: { $gt: 10 } } },
... verbosity: "executionStats"
... }
... )
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.product",
"indexFilterSet" : false,
"winningPlan" : {
"stage" : "COUNT",
"inputStage" : {
"stage" : "EOF"
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 0,
"executionTimeMillis" : 47,
"totalKeysExamined" : 0,
"totalDocsExamined" : 0,
"executionStages" : {
"stage" : "COUNT",
"nReturned" : 0,
"executionTimeMillisEstimate" : 0,
"works" : 1,
"advanced" : 0,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"nCounted" : 0,
"nSkipped" : 0,
"inputStage" : {
"stage" : "EOF",
"nReturned" : 0,
"executionTimeMillisEstimate" : 0,
"works" : 0,
"advanced" : 0,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1
}
}
},
"serverInfo" : {
"host" : "MCGL-4499",
"port" : 27017,
"version" : "4.2.7",
"gitVersion" : "51d9fe12b5d19720e72dcd7db0f2f17dd9a19212"
},
"ok" : 1
}
>
> var expv = db.geekFlareCol.explain("executionStats")
> expv.find( { product: "bread"} )
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "geekFlareDB.geekFlareCol",
"indexFilterSet" : false,
"parsedQuery" : {
"product" : {
"$eq" : "bread"
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"product" : {
"$eq" : "bread"
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 2,
"executionTimeMillis" : 0,
"totalKeysExamined" : 0,
"totalDocsExamined" : 6,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"product" : {
"$eq" : "bread"
}
},
"nReturned" : 2,
"executionTimeMillisEstimate" : 0,
"works" : 8,
"advanced" : 2,
"needTime" : 5,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"direction" : "forward",
"docsExamined" : 6
}
},
"serverInfo" : {
"host" : "MCGL-4499",
"port" : 27017,
"version" : "4.2.7",
"gitVersion" : "51d9fe12b5d19720e72dcd7db0f2f17dd9a19212"
},
"ok" : 1
}
>
44. Access Control in MongoDB
Access control features enable authentication access to existing users. For access control enabled DB to ensure to create a user admin role in admin DB.
- Connect DB without authentication.
- Switch to the database
use admin
- Create user like below
db.createUser( {user: “UserAdmin”, pwd: “password” ,role: [adminRole])
Example:
db.createUser(
... {
... user: "AdminUser",
... pwd: passwordPrompt(),
... roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
... }
... )
Enter password:
Successfully added user: {
"user" : "AdminUser",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
"readWriteAnyDatabase"
]
}
- Restart
mongod
instance - Access again with created user and password.
C:\Users\>mongo --port 27017 --authenticationDatabase "admin" -u "AdminUser" -p
MongoDB shell version v4.2.7
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
45. Retrieve and Delete access control user
The below command can be used to check the user info and delete it.
db.getUser("AdminUser")
db.dropUser("AdminUser")
Example:
> db.getUser("AdminUser")
{
"_id" : "admin.AdminUser",
"userId" : UUID("78d2d5bb-0464-405e-b27e-643908a411ce"),
"user" : "AdminUser",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.dropUser("AdminUser")
true
> db.getUser("AdminUser")
null
>
46. Grant User-defined Roles
MongoDB provides db.createRole()
method to specify the privileges to a user and an array of inherited roles.
- Connect MongoDB instance with admin User.
- Execute below command to generate a new role.
Syntax:
db.createRole({role:”roleName”,privileges:[{privilegeName}],roles:[InheritedArray]})
Example:
use admin
> db.createRole(
... {
... role: "abc",
... privileges: [ { resource: { db: "geekFlareDB", collection: "geekFlareCol" }, actions: [ "killop" ,"inprog"] } ],
... roles: []
... }
... )
{
"role" : "abc",
"privileges" : [
{
"resource" : {
"db" : "geekFlareDB",
"collection" : "geekFlareCol"
},
"actions" : [
"killop",
"inprog"
]
}
],
"roles" : [ ]
}
47. Revoke User-defined Roles
To modify the existing roles use below command.
Syntax: db.revokeRolesFromUser( userName, [{ "role" : roleName , db:dbName} ] )
Example:
> db.getUser("AdminUser")
{
"_id" : "admin.AdminUser",
"userId" : UUID("fe716ed1-6771-459e-be13-0df869c91ab3"),
"user" : "AdminUser",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.revokeRolesFromUser( "AdminUser", [{ "role" : "userAdminAnyDatabase" , db:"admin"} ] )
> db.getUser("AdminUser")
{
"_id" : "admin.AdminUser",
"userId" : UUID("fe716ed1-6771-459e-be13-0df869c91ab3"),
"user" : "AdminUser",
"db" : "admin",
"roles" : [
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
>
48. MongoDB Connectivity with Python
The pymongo package is required to connect MongoDB from python Console.
>>> from pymongo import MongoClient
>>> mClient=MongoClient("mongodb://127.0.0.1:27017/")
>>> mDB=mClient.geekFlareDB
>>> mRecord={"_id":4,"name":"XYZ"}
>>> mDB.geekFlareCollection.insert_one(mRecord)
<pymongo.results.InsertOneResult object at 0x000002CC44256F48>
>>> for i in mDB.geekFlareCollection.find({"_id":4}):
... print(i)
...
{'_id': 4, 'name': 'XYZ'}
>>>
What’s next?
Check out this list of NoSQL clients to manage MongoDB and other NoSQL databases. If your job involves frequently working on MongoDB then you may want to learn more from this Udemy course.