List of useful MongoDB commands

Shortcuts

MongoDB clients

There are many clients for MongoDB. The most notable ones are MongoDB Shell and MongoDB Compass.

Mongosh

Mongosh allows to write JavaScript code to interact with the database. For example to print all data from all collections,

let collections = db.getCollectionNames();
collections.forEach(c => db.getCollection(c).find().forEach(printjson));

Connect to the database,

$ mongosh mongodb://localhost:27017

Database interactions

> show databases
> db // Which database currently connected to
> use [database-name] // Switches to the database, even if not exist. With first insertion database is created
> show collections
> db.createCollection("user")

Create

In MongoDB, if a collection doesn’t exist, upon the first insertion the collection is created.

MongoDB guarantees atomicity at the individual document level.

> db.collection.insertOne()  // Inserts a single document
> db.user.insertOne({firstName: "John", lastName: "Wick", age: 40});
> db.collection.insertMany() // Inserts many documents
> db.collection.insertMany([{firstName: "John", lastName: "Wick", age: 40}, {firstName: "Robert", lastName: "McCall", age: 55}])

Query

> db.collection.find() // List all data in the collection
> db.user.find()
> db.user.find().pretty()

Export a collection with mongoexport

First, download MongoDB Database Tools. Then, run:

$ mongoexport --uri=[DB_URI] --db=[DB_NAME] --collection=[COLLECTION_NAME] --out=[PATH_FILE_NAME]

Ensure a collection is a timeseries collection

Timeseries is a special collection type that allows fast data aggregation, especially useful for stock market, weather, fleet, etc.

> db.getCollectionInfos({name:"quoteHistory"});

Should produce an output like this:

[
  {
    name: 'quoteHistory',
    type: 'timeseries',
    options: { timeseries: [Object] },
    info: { readOnly: false }
  }
]

Group by (find duplicate by a key)

db.COLLECTION_NAME.aggregate([
  {
    $group: {
      _id: "$FIELD_NAME",
      count: { $sum: 1 },
      duplicates: { $addToSet: "$_id" }
    }
  },
  {
    $match: {
      count: { $gt: 1 }
    }
  }
], { allowDiskUse: true })

Count group by

db.COLLECTION_NAME.aggregate([
  {
    $group: {
      _id: "$FIELD_NAME",
      count: { $sum: 1 },
      duplicates: { $addToSet: "$_id" }
    }
  },
  {
    $match: {
      count: { $gt: 1 }
    }
  },
  {
    $count: "total"
  }
], { allowDiskUse: true })