Friday, February 3, 2017

MongoDB cheat sheet


Steps involved to see the existing database

We need to know that MondoD is the command line and Mongo runs the command line

1) We need to start the mongoDB daemon
2) Go the the bin folder and type mongo
C:\Program Files\MongoDB\Server\3.4\bin>mongo



3)  Look for existing database
> show dbs
admin  0.000GB
local  0.000GB

Create new database

1) Follow the first 2 steps from above
2) Create new database by typing the following command
> use book
switched to db book


Drop a Database


1
2
3
4
5
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>


See existing collections

1) Follow the first 2 steps from above
2) See existing collections by typing the following command

Note: The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. mongodb collections should be in lowercase

> show collections

Create new collections

1) Follow the first 2 steps from above
2) Create new collection by typing the following command with the name
> db.createCollection('books')
{ "ok" : 1 }

Insert data to collections

1) Follow the first 2 steps from above
2) Insert data into the collections  

Note:Id would be automatically generated
db.genres.insert({name:'Suspense'})
WriteResult({ "nInserted" : 1 })

List data in collections  

1) Follow the first 2 steps from above
2) Use the find method to get the collection

 db.genres.find()
{ "_id" : ObjectId("58939a30fe7155f5e0274e0e"), "name" : "Suspense" }

List Formatted data in collections  

1) Follow the first 2 steps from above
2) Insert data into the collections

 db.book.find().pretty()
{
        "_id" : ObjectId("58939d9efe7155f5e0274e11"),
        "title" : "Murder House",
        "genre" : "Suspense",
        "description" : "Ocean drive is gorgeuos",
        "author" : "James paterson",
        "publisher" : "Amazon"
}
>
}

Drop a collection

1) Follow the first 2 steps from above
2) Use the drop method to drop the specified collection
db.Comppany.drop();
true
> show collections

Delete all documents from the collections

1) Follow the first 2 steps from above
2) Use the deleteMany method to drop all documents

db.Company.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }

Insert many documents to the collections

1) Follow the first 2 steps from above
2) The following example inserts three new documents into the users collection

db.users.insertMany(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)


Check for mongoose connection state in express

mongoose.set('debug', true);
// test.js
require('./app.js'); // which executes 'mongoose.connect()'

var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
Output - 0 = disconnected, 1 = connected, 2 = connecting, 3 = disconnecting

No comments:

Post a Comment