mongodb

22
MongoDB by Balaji Mani

Upload: balaji-mani

Post on 25-Nov-2015

1.446 views

Category:

Documents


0 download

DESCRIPTION

Basics of MongoDB and NOSQL.

TRANSCRIPT

The Great Team Lead/DBA Get Together

MongoDBby 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: Trimble} Company is the Key and the Value is Trimble.

MongoDB is Schema lessSchema 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.

Installationhttp://www.mongodb.org/downloadsNote: Always download the stable release.

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]}

Introduction to JSON(JavaScript Object Notation)

Nesting in JSONBasic Nestingdb.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.jsonSelecting 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()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: Helpto list the databases: show dbs Local database is an internal database used for activities like replication, sharding etcTo list collections: show collections Querying MONGODB: (Continuation )Operators in MongoDB:Query SelectorsNameDescription$gtMatches values that are greater than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1})$gteMatches values that are equal to or greater than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1})$inMatches any of the values that exist in an array specified in the query.db.inventory.find( { qty: { $in: [ 5, 15 ] } } )$ltMatches values that are less than the value specified in the query. db.products.find( {price:{$gte:200}},{name:1,price:1})$lteMatches values that are less than or equal to the value specified in the query. db.products.find( {price:{$lte:200}},{name:1,price:1})$neMatches all values that are not equal to the value specified in the query. db.inventory.find( { qty: { $ne: 20 } } ) $ninMatches values that do not exist in an array specified to the query.db.inventory.find( { qty: { $nin: [ 5, 15 ] } } ) NameDescription$orJoins query clauses with a logical OR returns all documents that match the conditions of either clause.$andJoins query clauses with a logical AND returns all documents that match the conditions of both clauses.$notInverts the effect of a query expression and returns documents that do not match the query expression.$norJoins query clauses with a logical NOR returns all documents that fail to match both clauses.

Logical (Continuation )ElementNameDescription$existsMatches documents that have the specified field.$typeSelects documents if a field is of the specified type.GeospatialNameDescription$modPerforms a modulo operation on the value of a field and selects documents with a specified result.$regexSelects documents where values match a specified regular expression.$whereMatches documents that satisfy a JavaScript expression.NameDescription$geoWithinSelects geometries within a bounding GeoJSON geometry.$geoIntersectsSelects geometries that intersect with a GeoJSON geometry.$nearReturns geospatial objects in proximity to a point.$nearSphereReturns geospatial objects in proximity to a point on a sphere. Evaluation Query Operators (Continuation )Sort Command:Db.collectionname.find({where,},{columns,}).sort()

Example:db.products.find( {},{name:1,price:1}).sort({price:1}) -- ascendingdb.products.find( {},{name:1,price:1}).sort({price:-1}) -- descendingdb.products.find({price:{$exists:true}},{name:1,price:1}).sort({price:-1})

null is always less than 0 NameDescription$incIncrements the value of the field by the specified amount.$renameRenames a field.$setOnInsertSets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents.$setSets the value of a field in an existing document.$unsetRemoves the specified field from an existing document.Update Operators(Continuation )Cursors in MongoDBCursors:for(var i=0;i