Mongodb

commands

Mon Dec 31 2018

Mongodb

To show databases:

show dbs

//To check in which database you are: 
db 


Create/switch a new database: 
use <database name> 

Create a user

db.createUser({
  user:"name",
  pwd:"password",
  roles:["readWrite", "dbAdmin"]
});

find() Method

db.COLLECTION_NAME.find().pretty()

//Less Than, Greater Than , Not Equals
db.COLLECTION_NAME.find({"number":{$lt:50}})
db.COLLECTION_NAME.find({"number":{$lte:50}})
db.COLLECTION_NAME.find({"number":{$gt:50}})
db.COLLECTION_NAME.find({"number":{$gte:50}})
db.COLLECTION_NAME.find({"number":{$ne:50}})

//Count 
db.COLLECTION_NAME.find({"number":{$ne:50}}).count()
db.COLLECTION_NAME.find().count()

//Sorting 
db.COLLECTION_NAME.find().sort({columnName: 1})

//Limit 
db.COLLECTION_NAME.find().limit(#)

//Find with and
db.COLLECTION_NAME.find(
   {
      $and: [
         {key1: value1}, {key2:value2}
      ]
   }
)

//Find with or
db.COLLECTION_NAME.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
)

db.COLLECTION_NAME.find(
  {"number": {$gt:50}, 
       $or: [
          {"title": "MongoDB"}
       ]
  }
)

Insert

db.COLLECTION_NAME.insert({ title: "one", number: 10 })

//Many
db.COLLECTION_NAME.insert( 
[
  { title: "one", number: 10 },
  { title: "two", number: 20}
]
)

Update

db.COLLECTION_NAME.update({'title':'title1'},
  {
    $set:{'title':'title2'}
  }
)

Update One

try {
   db.COLLECTION_NAME.updateOne(
      { "title" : "title2" },
      { $set: { "number" : 3 } }
   );
} catch (e) {
   print(e);
}

Update Many

try {
   db.COLLECTION_NAME.updateMany({ number: { $gt: 4 } },
      { 
       $set: { "Review" : true } 
       $set: { 'url': 'test'}
      }
   );
} catch (e) {
   print(e);
}

Copy Collection

db.COLLECTION_NAME.copyTo('NEW_COLLECTION_NAME');
db.OLD_COLLECTION_NAME.drop();
Loading...
Deepak Mishra

Deepak Mishra #JavaScript, #Node, #React #Angular, #jQuery, #HTML5, #CSS blog

  • www.deepakmihsra.com