Skip to content
⚙ I / O Briefs

Mongo DB cheat sheet

Technology1 min read

mongo db

Show All Databases

1show dbs

Show Current Database

1db

Create Or Switch Database

1use acme

Drop

1db.dropDatabase()

Create Collection

1db.createCollection('posts')

Show Collections

1show collections

Insert Row

1db.posts.insert({
2 title: 'Post One',
3 body: 'Body of post one',
4 category: 'News',
5 tags: ['news', 'events'],
6 user: {
7 name: 'John Doe',
8 status: 'author'
9 },
10 date: Date()
11})

Insert Multiple Rows

1db.posts.insertMany([
2 {
3 title: 'Post Two',
4 body: 'Body of post two',
5 category: 'Technology',
6 date: Date()
7 },
8 {
9 title: 'Post Three',
10 body: 'Body of post three',
11 category: 'News',
12 date: Date()
13 },
14 {
15 title: 'Post Four',
16 body: 'Body of post three',
17 category: 'Entertainment',
18 date: Date()
19 }
20])

Get All Rows

1db.posts.find()

Get All Rows Formatted

1db.find().pretty()

Find Rows

1db.posts.find({ category: 'News' })

Sort Rows

1# asc
2db.posts.find().sort({ title: 1 }).pretty()
3# desc
4db.posts.find().sort({ title: -1 }).pretty()

Count Rows

1db.posts.find().count()
2db.posts.find({ category: 'news' }).count()

Limit Rows

1db.posts.find().limit(2).pretty()

Chaining

1db.posts.find().limit(2).sort({ title: 1 }).pretty()

Foreach

1db.posts.find().forEach(function(doc) {
2 print("Blog Post: " + doc.title)
3})

Find One Row

1db.posts.findOne({ category: 'News' })

Find Specific Fields

1db.posts.find({ title: 'Post One' }, {
2 title: 1,
3 author: 1
4})

Update Row

1db.posts.update({ title: 'Post Two' },
2{
3 title: 'Post Two',
4 body: 'New body for post 2',
5 date: Date()
6},
7{
8 upsert: true
9})

Update Specific Field

1db.posts.update({ title: 'Post Two' },
2{
3 $set: {
4 body: 'Body for post 2',
5 category: 'Technology'
6 }
7})

Increment Field (\$inc)

1db.posts.update({ title: 'Post Two' },
2{
3 $inc: {
4 likes: 5
5 }
6})

Rename Field

1db.posts.update({ title: 'Post Two' },
2{
3 $rename: {
4 likes: 'views'
5 }
6})

Delete Row

1db.posts.remove({ title: 'Post Four' })

Sub-Documents

1db.posts.update({ title: 'Post One' },
2{
3 $set: {
4 comments: [
5 {
6 body: 'Comment One',
7 user: 'Mary Williams',
8 date: Date()
9 },
10 {
11 body: 'Comment Two',
12 user: 'Harry White',
13 date: Date()
14 }
15 ]
16 }
17})

Find By Element in Array (\$elemMatch)

1db.posts.find({
2 comments: {
3 $elemMatch: {
4 user: 'Mary Williams'
5 }
6 }
7 }
8)

Add Index

1db.posts.createIndex({ title: 'text' })

Text Search

1db.posts.find({
2 $text: {
3 $search: "\"Post O\""
4 }
5})

Greater & Less Than

1db.posts.find({ views: { $gt: 2 } })
2db.posts.find({ views: { $gte: 7 } })
3db.posts.find({ views: { $lt: 7 } })
4db.posts.find({ views: { $lte: 7 } })