MongoDB Notes

Table of Contents

Check monosh Version

Open a connection to your local MongoDB instance. All other commands will be runw ithin this mongosh connection.

mongosh --version

Start the Mongo Shell

mongosh "YOUR_CONNECTION_STRING" --username YOUR_USER_NAME

Show Current Database

Show current database name

db

Show All Databases

Show all databases in the current MongoDB instance

show dbs

Create Or Switch Database

Creates the database if does not exist else switch to the existing database

use blog

Drop Database

Delete the current database

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections

Show all collections in the current database

show collections

Insert Document

Create a new document inside the specified collection

db.posts.insertOne({
  title: 'Post 1',
  body: 'Body of post.',
  category: 'News',
  likes: 1,
  tags: ['news', 'events'],
  date: Date()
})

Insert Multiple Documents

Create a new document inside the specified collection

db.posts.insertMany([
  {
    title: 'Post 2',
    body: 'Body of post.',
    category: 'Event',
    likes: 2,
    tags: ['news', 'events'],
    date: Date()
  },
  {
    title: 'Post 3',
    body: 'Body of post.',
    category: 'Tech',
    likes: 3,
    tags: ['news', 'events'],
    date: Date()
  },
  {
    title: 'Post 4',
    body: 'Body of post.',
    category: 'Event',
    likes: 4,
    tags: ['news', 'events'],
    date: Date()
  },
  {
    title: 'Post 5',
    body: 'Body of post.',
    category: 'News',
    likes: 5,
    tags: ['news', 'events'],
    date: Date()
  }
])

Find All Documents

db.posts.find()

Find Documents with Query

Find all documents that match the filter obejct

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

Sort Documents

Sort the results of a find by the given fields Get all users sorted by name in alphabetical order and then if nay names are the same sort by aga in reverse order

Ascending

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

Descending

db.posts.find().sort({ title: -1 })

Count Documents

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

Limit Documents

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

Chaining

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

Find One Document

db.posts.findOne({ likes: { $gt: 3 } })

Update Document

db.posts.updateOne({ title: 'Post 1' },
{
  $set: {
    category: 'Tech'
  }
})

Update Document or Insert if not Found

db.posts.updateOne({ title: 'Post 6' },
{
  $set: {
    title: 'Post 6',
    body: 'Body of post.',
    category: 'News'
  }
},
{
  upsert: true
})

Increment Field ($inc)

db.posts.updateOne({ title: 'Post 1' },
{
  $inc: {
    likes: 2
  }
})

Update Multiple Documents

db.posts.updateMany({}, {
  $inc: {
    likes: 1
  }
})

Rename Field

db.posts.updateOne({ title: 'Post 2' },
{
  $rename: {
    likes: 'views'
  }
})

Delete a Document

db.posts.deleteOne({ title: 'Post 6' })

Delete Multiple Documents

db.posts.deleteMany({ category: 'Tech' })

Greater & Less Than

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

Complex Filter Object

Check for equality

Get all users with the name DEVANG

db.users.find({name: {$eq :"DEVANG"}})

Check for inequality

Get all the users with a name other than DEVANG

db.users.find((name: {&ne :"DEVANG"}))

Check for > & >=

Get all uses with an age greater than 12 Get all users with an age greater than or equal to 15

$gt/$gte
db.users.find({age: {$gt:12}})
db.users.find({age: {$gte:15}})

Check for < & <=

Get all uses with an age less than 12 Get all users with an age less than or equal to 15

$lt/$lte
db.users.find({age: {$lt:12}})
db.users.find({age: {$lte:15}})

Check for more than one

Get all users with a name of Swastik or Shubham

$in
db.users.find({age: {$in:["Shubham","Swastik"]}})

Check if a value is none of many values

Get all users that do not have the name Swastik or Shubham

$nin
db.users.find({ name: { $nin: ["Shubham", "Swastik"] } })

Check that multiple conditions are all true

Get all users that have an age of 19 and the name Shubham This is an alternative way to do the same thing. Generally you do not need $and

$and
db.users.find({ $and: [{ age: 19 }, { name: "Swastik" }] })
db.users.find({ age: 19, name: "Shubham" })

Check that one of multiple conditions is true

Get all users with a name of Swastik or an age of 19

$or
db.users.find({ $or: [{ age: 19 }, { name: "Swastik" }] })

Negate the filter inside of $not

Get all users with a name other than Devang

db.users.find({ name: { $not: { $eq: "Devang" } } })

Check if a field exists

Get all users that have a name field

db.users.find({ name: { $exists: true } })