Overview

The aim of this post is to list out commonly and sometimes rarely used MongoDB commands, queries and Aggregation framework. To install MongoDB community server, please follow

Setting Up MongoDB Community Server

You can also refer the MongoDB documentation for an enhanced info.

Commands

Show Databases

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Create Database

use {database name}

eg:

> use universe
switched to db universe

Create Collection

db.createCollection({planet_name})

> db.createCollection('planet')
{ "ok" : 1 }

Show Collections

show collections

> show collections
planet

Drop Collection

db.{collection_name}.drop()

> db.planet.drop()
true

Drop Database

db.dropDatabase()

> db.dropDatabase()
{ "dropped" : "universe", "ok" : 1 }

Insert a Document

db.{collection_name}.insert({document})

> db.planet.insert({
     name: 'Mars',
     numberOfMoons: 2
  })
WriteResult({ "nInserted" : 1 })

Query Document

db.{collection_name}.find()

> db.planet.find()
{ "_id" : ObjectId("5dc1415563b4683f19487261"), "name" : "Mars", "numberOfMoons" : 2 }

Query document with a field value

db.{collection_name}.find({query})

eg:

> db.planet.find({"name" : "Mars"})
{ "_id" : ObjectId("5dc1415563b4683f19487261"), "name" : "Mars", "numberOfMoons" : 2 }

Update a Document

db.{collection_name}.update({criteria}, {update})

Eg:

> db.planet.updateOne(
      { name: "Mars" },
      {
        $set: { "numberOfMoons": 3 }
      }
   )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Delete Document

db.{collection_name}.deleteOne(query)

Eg:

> db.planet.deleteOne({"name" : "Mars"})
 { "acknowledged" : true, "deletedCount" : 1 }

Project field

db .{collection_name} .find( {query,} { projection } )

Eg:

> db.planet.find({}, { name: 1, numberOfMoons: 1, _id: 0 } )
 { "name" : "Earth", "numberOfMoons" : 1 }
 { "name" : "Mars", "numberOfMoons" : 2 }

Create Single Index

> db.planet.createIndex( { name: 1 } )
 {
         "createdCollectionAutomatically" : false,
         "numIndexesBefore" : 1,
         "numIndexesAfter" : 2,
         "ok" : 1
 }

Compound Index

 > db.planet.createIndex( { name: 1, numberOfMoons: 1 } )
 {
         "createdCollectionAutomatically" : false,
         "numIndexesBefore" : 2,
         "numIndexesAfter" : 3,
         "ok" : 1
 }

Show all indexes

> db.planet.getIndexes()

Drop Index

Conclusion

I’ll like to keep this page as a quick reference and will keep on adding/updating commands.

Credits: Photo by Fernando Hernandez on Unsplash