Sunday, 8 September 2019

Mongodb index commands with examples

Mongodb index commands with examples

Create OR Use existing Database
use bank;



Create a new collection.
db.createCollection("users");



Add Records in collection.
db.users.insert([{"isActive":false,"balance":"$3,960.64","age":30,"eyeColor":"blue","name":"Dawn Keith","gender":"female","company":"COSMOSIS","email":"dawnkeith@cosmosis.com","phone":"+1 (839) 437-3421","address":"392 Clifford Place, Fontanelle, Arizona, 2687"},{"isActive":false,"balance":"$1,280.14","age":31,"eyeColor":"green","name":"Bettie Eaton","gender":"female","company":"COMTREK","email":"bettieeaton@comtrek.com","phone":"+1 (861) 460-2317","address":"203 Allen Avenue, Elrama, North Carolina, 4453"},{"isActive":true,"balance":"$2,042.37","age":38,"eyeColor":"green","name":"Margie Ayala","gender":"female","company":"VOIPA","email":"margieayala@voipa.com","phone":"+1 (941) 569-2231","address":"111 Schroeders Avenue, Suitland, Louisiana, 7042"},{"isActive":false,"balance":"$3,170.35","age":37,"eyeColor":"blue","name":"Baker Townsend","gender":"male","company":"EVIDENDS","email":"bakertownsend@evidends.com","phone":"+1 (808) 500-2793","address":"190 Just Court, Canoochee, Alabama, 325"}]);



Get all records
db.users.find().pretty();




Analyse the Query
db.users.find().explain("executionStats");



Add Index on collection
db.users.ensureIndex({"age":1});



Get all indexes on collection.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  },
  {
    "v": 1,
    "key": {
      "age": 1
    },
    "name": "age_1",
    "ns": "bank.users"
  }
]



Delete Index on collection.
db.users.dropIndex({"age":1});
Output
{
  "nIndexesWas": 2,
  "ok": 1
}



Drop all indexes.
db.users.dropIndexes();
Output
{
  "nIndexesWas": 1,
  "msg": "non-_id indexes dropped for collection",
  "ok": 1
}



Check Indexes, after droping an index.
db.users.getIndexes();
Output
[
  {
    "v": 1,
    "key": {
      "_id": 1
    },
    "name": "_id_",
    "ns": "bank.users"
  }
]



ReIndex the collecton.
db.users.reIndex()
Output
{
  "nIndexesWas": 1,
  "nIndexes": 1,
  "indexes": [
    {
      "key": {
        "_id": 1
      },
      "name": "_id_",
      "ns": "bank.users"
    }
  ],
  "ok": 1
}



Simple Aggregate Example
db.users.aggregate({$group:{_id:"$age",total:{$sum:1}}});
Output
{
  "_id": 37,
  "total": 1
}{
  "_id": 38,
  "total": 1
}{
  "_id": 31,
  "total": 1
}{
  "_id": 30,
  "total": 2
}



Average Aggregate Example
db.users.aggregate({$group:{_id:"$gender",avgAge:{$avg:"$age"}}});
Output
{
  "_id": "female",
  "avgAge": 32.25
}{
  "_id": "male",
  "avgAge": 37
}



Max Value in Aggregate
db.users.aggregate({$group:{_id:"$gender",richest:{$max:"$balance"}}});
Output
{
  "_id": "female",
  "richest": "$3,960.64"
}{
  "_id": "male",
  "richest": "$3,170.35"
}