Skip to main content

MongoDB - Basic Commands

Greetings!

These are the basic MongoDB commands we use in our day-today work. Adding as a reference to myself :)

Create database

use DATABASE_NAME
$ use my_database

Show databases

$ show dbs

Connect to database

use DATABASE_NAME
$ use my_database

Drop database

db.dropDatabase()

Create Collection

DB.COLLECTION_NAME.(OPTIONS)
$ db.products.({ name: "Fruit Juice" })

Show collections

$ show collections

Drop collection

db.COLLECTION_NAME.drop()
$ db.products.drop()

Insert document

db.COLLECTION_NAME.insert(DOCUMENT)
$ db.products.insert({
item_name: "Frui Juice",
item_description: "sdfsdklf",
price: "100"
})

Read document

db.COLLECTION_NAME.find()
db.COLLECTION_NAME.find().pretty()
$ db.products.find().pretty()
$ db.products.find({ item_name: "Fruit Juice" }).pretty()

Like statement - we have to use regex
$ db.products.find( { item_name: { $regex: /789$/ } } )

AND
$ db.COLLECTION_NAME.find(
   {
      $and: [
         { key1: value1 }, { key2:value2 }
      ]
   }
).pretty()

OR
$ db.COLLECTION_NAME.find(
   {
      $or: [
         { key1: value1 }, { key2:value2 }
      ]
   }
).pretty()

Update document

db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
$ db.products.update({
{ item_name: "Frui Juice" },
{ price: 120 }
})

Delete document

db.COLLECTION_NAME.remove(CRITERIA)
$ db.products.remove({})
$ db.products.remove({ item_name: "Fruit Juice" })

Projection

Selecting only required fields
db.COLLECTION_NAME.find({}, { FIELD_NAME: 1 })
$ db.products.find({}, { item_name: 1 })
_id field is always displayed.
$ db.products.find({}, { item_name: 1, _id: 0 })

Limiting records

db.COLLECTION_NAME.find().limit(NUMBER)
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
$ db.products.find({}).limit(5)
$ db.products.find({}).limit(5).skip(2)

Sorting records

db.COLLECTION_NAME.find().sort({ KEY: 1 })
1 - ascending, -1 - descending
default to ascending
$ db.products.find({}).sort({ title: -1})

Create index

db.COLLECTION_NAME.ensureIndex({ KEY:1 })
1, -1 are orders
$ db.products.ensureIndex({ item_name: 1 })


Comments