Friday, August 19, 2016

MongoDB Basics -2


**********************************
 GET DB NAME
**********************************

To get current DB name use :



> db.getName()
test

**********************************
GET PREVIOUS ERROR IN SESSION
**********************************

To get previous error for the MongoDB use below query :



> db.getPrevError()
{ "err" : null, "n" : 0, "nPrev" : -1, "ok" : 1 }



**********************************
CHECK MONGODB hostInfo
**********************************

To get the host info for the MongoDB use below query :



> db.hostInfo()
{
        "system" : {
                "currentTime" : ISODate("2016-08-19T15:12:29.998Z"),
                "hostname" : "OMA-508353L",
                "cpuAddrSize" : 64,
                "memSizeMB" : 16009,
                "numCores" : 8,
                "cpuArch" : "x86_64",
                "numaEnabled" : false
        },
        "os" : {
                "type" : "Windows",
                "name" : "Microsoft Windows 7",
                "version" : "6.1 SP1 (build 7601)"
        },
        "extra" : {
                "pageSize" : NumberLong(4096)
        },
        "ok" : 1
}

create Collections in MongoDB

Syntax:
Basic syntax of createCollection() command is as follows

db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection

Change Your DB to DB where you want to create collections:

> use test
switched to db test

> db
test

> show collections
>
>
> db.createCollection("TESTCOLLECTION", { capped : true, autoIndexID : true, size : 61428, max : 100 } )
{ "ok" : 1 }

> show collections
TESTCOLLECTION
mycol
tutorialspoint
>

capped    Boolean    (Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.

autoIndexID    Boolean    (Optional) If true, automatically create index on _id field.s Default value is false.

size    number    (Optional) Specifies a maximum size in bytes for a capped collection. If If capped is true, then you need to specify this field also.

max    number    (Optional) Specifies the maximum number of documents allowed in the capped collection.

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Basic syntax of createCollection() method without options is as follows:

> db.createCollection2("TESTCOLLECTION2")

> db.tutorialspoint.insert({"name" : "tutorialspoint"})
WriteResult({ "nInserted" : 1 })

> show collections
mycol
tutorialspoint
>

Connecting to MongoDB


Change your directory to oracle 

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\System32>cd C:\MongoDB

C:\MongoDB>mongo.exe
'mongo.exe' is not recognized as an internal or external command,
operable program or batch file.

C:\MongoDB>cd bin

C:\MongoDB\bin>mongo.exe
2016-08-19T09:26:16.495-0500 I CONTROL  [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
MongoDB shell version: 3.2.4
connecting to: test
>
> db.help()
DB methods:
        db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
        db.auth(username, password)
        db.cloneDatabase(fromhost)
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost)
        db.createCollection(name, { size : ..., capped : ..., max : ... } )
        db.createUser(userDocument)
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval() - deprecated
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnlock() unlocks server following a db.fsyncLock()
        db.getCollection(cname) same as db['cname'] or db.cname
        db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getLogComponents()
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow queries on a replication slave server
        db.getName()
        db.getPrevError()
        db.getProfilingLevel() - deprecated
        db.getProfilingStatus() - returns if profiling is on and slow threshold
        db.getReplicationInfo()
        db.getSiblingDB(name) get the db at the same server as this one
        db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
        db.hostInfo() get details about the server's host
        db.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.loadServerScripts() loads all the scripts in db.system.js
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printShardingStatus()
        db.printSlaveReplicationInfo()
        db.dropUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
        db.serverStatus()
        db.setLogLevel(level,<component>)
        db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
        db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
        db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
        db.setVerboseShell(flag) display extra information in shell output
        db.shutdownServer()
        db.stats()
        db.version() current version of the server
>

Friday, April 1, 2016

Install Mongo DB cmd line

Install MongoDB On Windows
To install the MongoDB on windows, first download the latest release of MongoDB from http://www.mongodb.org/downloads Make sure you get correct version of MongoDB depending upon your windows version. To get your windows version open command prompt and execute following command.

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.


C:\MongoDB\bin>wmic os get osarchitecture
OSArchitecture
64-bit

Install MongoDB for Windows.
Change to the directory containing the .msi installation binary of your choice and invoke:

 Directory of C:\MongoDB

03/29/2016  04:40 PM    <DIR>          .
03/29/2016  04:40 PM    <DIR>          ..
03/29/2016  04:38 PM        97,922,560 mongodb-win32-x86_64-3.2.4-signed.msi
               1 File(s)     97,922,560 bytes
               2 Dir(s)  43,619,405,824 bytes free

C:\MongoDB>msiexec.exe /q /i mongodb-win32-x86_64-3.2.4-signed.msi INSTALLLOCATION="C:\MongoDB" ADDLOCAL="all"

C:\MongoDB>


Configure a Windows Service for MongoDB Community Edition

Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command Prompt as Administrator.

Execute the remaining steps from the Administrator command prompt.
   
Create directories.

Create directories for your database and log files:

mkdir c:\data\db
mkdir c:\data\log


3
Create a configuration file.

Create a configuration file. The file must set systemLog.path. Include additional configuration options as appropriate.

For example, create a file at C:\mongodb\mongod.cfg that specifies both systemLog.path and storage.dbPath:

C:\MongoDB\bin>notepad C:\mongodb\mongod.cfg

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db


   
Install the MongoDB service.

IMPORTANT
Run all of the following commands in Command Prompt with “Administrative Privileges”.
Install the MongoDB service by starting mongod.exe with the --install option and the -config option to specify the previously created configuration file.
   
C:\MongoDB\bin>mongod.exe --config "C:\mongodb\mongod.cfg" --install

C:\MongoDB\bin>

To use an alternate dbpath, specify the path in the configuration file (e.g. C:\mongodb\mongod.cfg) or on the command line with the --dbpath option.

   
Start the MongoDB service.

C:\MongoDB\bin>net start MongoDB

The MongoDB service was started successfully.


C:\MongoDB\bin>

Dropping collections-MongoDB

> db.COLLECTION_NAME.drop()
false

> show collections
mycol
mycollection
tutorialspoint

> db.mycol.drop()
true

> show collections
mycollection
tutorialspoint


> show collections
mycollection
tutorialspoint

> db.mycollection.drop()
true

> db.tutorialspoint.drop()
true

> show collections
>

Wednesday, March 30, 2016

MONGO DB BASICS

*******************************
LOGIN INTO MONGO DATABASE
*******************************

C:\MongoDB\bin>mongo.exe
2016-03-30T10:31:31.317-0500 I CONTROL  [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
MongoDB shell version: 3.2.4
connecting to: test
> show dbs
local  0.000GB

*******************************
USE MYDB DATABASE
*******************************

> use mydb
switched to db mydb
> show dbs
local  0.000GB
> db
mydb

**********************************
Insert into MYDB
**********************************
> db.movie.insert({"name":"tutorials point"})
WriteResult({ "nInserted" : 1 })
> show dbs
local  0.000GB
mydb   0.000GB

*******************************
DROP MYDB DATABASE
*******************************

If you want to drop a database in MONGO DB <mydb>, then dropDatabase() command would be as follows:

1. change your current DB to MYDB
2. Drop using below cmd.

> use mydb
switched to db mydb

> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
local  0.000GB
>

*******************************
CHECK MONGODB VERSION
*******************************


> db.version()
3.2.4

Wednesday, July 22, 2015

Querying data from Mongodb



-- limit output where position : Center results  --

db.player.find(
{"position" : "Center"}

)

-- limit output where position : Center results & display only name values --

db.player.find(
{"position" : "Center"},
{"name":1}

)


-- limit output to 3 results --

db.player.find(
{"position" : "Center"},
{"name":1,_id:0}
).limit(3)

-- skip first 3 results --

db.player.find(
{"position" : "Center"},
{"name":1,_id:0}
).skip(3)


-- output to 2 values per doc & search criteria is filtered by position "or" id --

db.player.find(
{
  $or:[{"position":"Right Wing"},
  {"id":8475761}]
},{"name":1}
).pretty()