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] --collection [COLLECTION_NAME] --out [PATH_FILE_NAME]