Skip to content

Instantly share code, notes, and snippets.

@sabuhish
Forked from dipaktelangre/basic-mongo-queries.js
Created April 11, 2020 15:27
Show Gist options
  • Save sabuhish/60ab17225f82fdd31304d0814cabba9b to your computer and use it in GitHub Desktop.
Save sabuhish/60ab17225f82fdd31304d0814cabba9b to your computer and use it in GitHub Desktop.
MongoDB: Indexing - Create, Update, Delete and Analyze MongoDb Indexes
//show databases
show dbs
//Use Database test
use test
// show collections from the database
show collections
// show counts of records in collection
db.employee.count()
//find all
db.employee.find({}) // it only show first page of data
//find with query matching
db.employee.find({name: "Dipak"})
// count with query matching
db.employee.count({name: "Dipak"})
//count with find
db.employee.find({name: "Dipak"}).count()
//Query planner of the query
db.employee.find({name: "Dipak"}).explain()
// Query planner as well execution status of the query
db.employee.find({name: "Dipak"}).explain("executionStats")
//show indexes on collection
db.employee.getIndexes()
//create single key index
db.employee.createIndex({name: 1})
db.employee.createIndex({department: 1})
// create index in desc order
db.employee.createIndex({department: -1})
//create index with name
db.employee.createIndex({department: 1}, {name: "dept_index"})
// create index in background
db.employee.createIndex({department: 1}, { background: true })
// create multi key index
db.employee.createIndex({name:1, department:1})
// drop specific index
db.employee.dropIndex("dept_index")
// drop all indexes
db.employee.dropIndexes()
// Modify index
// Drop existing index and create new index again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment