Вы находитесь на странице: 1из 22

MongoDB

by Balaji Mani

What is MongoDB?
MongoDB is a Non-Relational Data Store for JSON document. By Non-Relational we mean that it does not store data in tables like Relational Databases does. JSON: JavaScript Object Notation. A very simple JSON document Looks like ,Company: TrimbleCompany is the Key and the Value is Trimble.

MongoDB is Schema less


Schema less means two documents doesnt need to have the same schema but we can create Dynamic Schema that can resolve on the fly. You can create two similar document in the same collection as below. ,Company: Trimble,Company: Trimble, Division: VSS, Location: Chennai-

Where MongoDB stands in a Scale of Scalability and Performance Vs. Functionality?

What's missing in MongoDB?


MongoDB has omitted functionalities like Joins and Transactions for better scalability. For example, We cannot do a join between two collections. The reason why we dont need transactions in MongoDB is because the documents are stored Hierarchical and can be accessed atomically so we dont need transactions between multiple collections.

RDBMS are known to Scale up by adding more and more hardware resources but they cannot scale out by adding commodity hardware.

A high level overview of an application using MongoDB.

Node.js is nothing but a C++ program that runs on the application node. We can Control Node.js using V8 JavaScript. Any application your write using node.js will be written in JavaScript. Node.js communicates to MongoDB using driver which contains a library of APIs for communicating with MongoDB.

Installation
http://www.mongodb.org/downloads Note: Always download the stable release.

Introduction to JSON
(JavaScript Object Notation)
Basic Structure: ,Company: Trimble A simple example of JSON document in Mongo Shell.

An Example of JSON Document with Hierarchy. ,a:1, b:2, Company: * Trimble, VSS, Chennai+-

Nesting in JSON
Basic Nesting
db.mycollection.insert({a:1, b:2, Company: [ "Trimble", "VSS", "Chennai"]})

Deep Nesting
db.mycollection.insert({ "class": "Mongodb", "Students":[ { "name":"Trimble", "activities": [ { "name" : "Production", "type" : "support" }, { "name" : "Titans", "type" : "developement" } ] } ] })

Querying MONGODB:

Mongoimport utility is used to import data into MongoDB. Loading example data: Product.json Command: Mongoimport --db pcat --collection products < products.json Selecting your data: db.products.find() will give you only limited rows. db.products.count() count of rows. To select only one field (column) db.products.find({},{name:1}) Selection one record. (top 1) db.products.findOne() To have a readable output: db.products.find().toArray() will load everything into the memory causing performance issues. db.products.find().pretty() will not load into memory. To limit the number of records listed. db.products.find().limit(5).toArray()

Querying MONGODB:
(Continuation ) To skip N number of rows. db.products.find({ }).limit(4).skip(2) { } is nothing but the where clause. Removing the id column. db.products.find({},{name:1,_id:0}) To select more than one field. db.products.find({},{name:1,brand:1}) Selecting based on the primary key Objectid. db.products.findOne( {"_id":ObjectId("507d95d5719dbef170f15bfe")}) selective columns with where clause. db.products.find( {_id:"ac3"},{name:1,price:1}) db.products.find( {price:200},{name:1,price:1}) For Help: Help to list the databases: show dbs Local database is an internal database used for activities like replication, sharding etc To list collections: show collections

Operators in MongoDB:
Query Selectors
Name $gt Description Matches values that are greater than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1}) Matches values that are equal to or greater than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1}) Matches any of the values that exist in an array specified in the query. db.inventory.find( { qty: { $in: [ 5, 15 ] } } ) Matches values that are less than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1}) Matches values that are less than or equal to the value specified in the query. db.products.find( {price:{$lte:200}},{name:1,price:1}) Matches all values that are not equal to the value specified in the query. db.inventory.find( { qty: { $ne: 20 } } ) Matches values that do not exist in an array specified to the query. db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )

$gte

$in

$lt

$lte

$ne $nin

Logical
Name
$or $and $not $nor

(Continuation )

Description
Joins query clauses with a logical OR returns all documents that match the conditions of either clause. Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. Inverts the effect of a query expression and returns documents that do not match the query expression. Joins query clauses with a logical NOR returns all documents that fail to match both clauses.

Element
Name $exists $type Description Matches documents that have the specified field. Selects documents if a field is of the specified type.

Evaluation Query Operators


Name $mod $regex Description

(Continuation )

Performs a modulo operation on the value of a field and selects documents with a specified result. Selects documents where values match a specified regular expression.

$where

Matches documents that satisfy a JavaScript expression.

Geospatial
Name $geoWithin $geoIntersects $near $nearSphere Description Selects geometries within a bounding GeoJSON geometry. Selects geometries that intersect with a GeoJSON geometry. Returns geospatial objects in proximity to a point. Returns geospatial objects in proximity to a point on a sphere.

Update Operators
Name
$inc $rename $setOnInsert $set $unset

(Continuation )

Description
Increments the value of the field by the specified amount. Renames a field.

Sets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents.
Sets the value of a field in an existing document. Removes the specified field from an existing document.

Sort Command: Db.collectionname.find({where,},{columns,}).sort() Example: db.products.find( {},{name:1,price:1}).sort({price:1}) -- ascending db.products.find( {},{name:1,price:1}).sort({price:-1}) -- descending db.products.find({price:{$exists:true}},{name:1,price:1}).sort({price:-1})

null is always less than 0

Cursors in MongoDB
Cursors: for(var i=0;i<20000;i++) {db.test.insert({x:i,y:"hi"});} For help: Db.products.find().help() cursor methods db.test.find({x:19000}) { "_id" : ObjectId("53352d4024e9897b01cb2d58"), "x" : 19000, "y" : "hi" } var cursor=db.test.find(); cursor.hasNext() -- True cursor.next() { "_id" : ObjectId("53352d3f24e9897b01cae320"), "x" : 0, "y" : "hi" } To select till hasNext() is false, var cursor=db.test.find();while(cursor.hasNext())printjson(cursor.next()); To select only one column, var cursor=db.test.find();while(cursor.hasNext())printjson(cursor.next().x);

Insert in MongoDB
Insert statement: Db.temperature.insert({x:3,y:4}) x={name:"Bluetooth Headset 509", type: ["accessory","headset"], price:30} db.products.insert(x) To find errors after a command executed. db.getLastError() Description of getLastError. db.getLastErrorObj() To view the index. db.products.getIndexes() Example of duplicate key error: Db.products.insert(,_id:ac3-)

Notes: Bulk insert is also present in MongoDB.

Update in MongoDB
Two types of updates. Full document update. db.test.update( { }, { "_id" : 100, "x" : "hello world", y:123 }) Partial update. db.test.update( { _id : 100}, { "_id" : 100, "x" : "hello world", y:123 }) $set $push $addtoset $pop $unset

Reference: http://docs.mongodb.org/manual/reference/method/db.collection.update/ UPSERT statement. Db.test.update({_id:"/sports/football"},{$inc:{views:1}},true)

Remove or Delete in MongoDB


Delete statement: db.test.remove({_id:100}) Delete all records: db.test.remove({}) Expressional delete: db.test2.remove({x:/ello/}) Hierarchical Delete: { _id: ObjectId("508"), name: "Jane", likes: ["tennis","golf"], registered: false, affr: { city: "Lyon", country: "France" } } db.users.remove({"addr.city":"Lyon",registered:false})

Commands in MongoDB
Instance Type: db.runCommand({isMaster:1}] Or db.runCommand(isMaster) To look at help: db.isMaster other helps: db.help() ServerStatus: db.serverStatus() what is currently running in the server: db.currentOp() To kill a opid: db.killOp() Create index: db.products.ensureIndex({name:1}) Running a query and getting the execution plan: db.products.find({name:"AC3 Case Red"}) db.products.find({name:"AC3 Case Red"}).explain() To list indexes: db.products.getIndexes() -- Indexes are b-tree in MongoDB we can also query the system catalog to query the indexes: db.system.indexes.find() help on a collection: db.products.help() To Drop an index: db.products.dropIndex({name:1}) To drop a collection: Db.products.drop() To delete all the data in a collection: Db.products.remove({}) Namespace catalog: db.system.namespaces.find() To list the databases info: db.runCommand({listDatabases:1}) --use admin

Thank You

Вам также может понравиться