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
>