Mongo db basics


Published on

This Presentation gives you basic understanding of MongoDB database .

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Mongo db basics

  2. 2. INTRODUCTION • MongoDB is a schema-free document database written in C++ and developed in an open-source project which is mainly driven by the company 10gen Inc that also offers professional services around MongoDB. • the main goal of MongoDB is to close the gap between the fast and highly scalable key-/value-stores and feature-rich traditional RDBMSs relational database management systems. • A database contains one or more collections consisting of documents. • MongoDB is schema-free the documents within a collection may be heterogeneous although the • Once the first document is inserted into a database, a collection is created automatically and the inserted document is added to this collection. It store data (which is in BSON – “Binary Serialized Document Notation” ) format
  3. 3. Advantage Documents are independent units which makes performance better (related data is read contiguously off disk) and makes it easier to distribute data across multiple servers. Application logic is easier to write. You don’t have to translate between objects in your application and SQL queries, you can just turn the object model directly into a document Non-relational databases are highly scalable than the relational databases. Non-relational databases process data faster than the relational databases because they do not use ACID properties. Non-relational databases are very flexible than the relational databases because they are schemaless.
  4. 4. Disadvantage Non-relational databases are less reliable than the relational databases because they compromise reliability for performance. Non-relational databases alsocompromise consistency for performance In many non-relational databases security is lesser than relational databases which is a major concern. Like Mongodb and Cassandra both databases have lack of encryption for data files, they have very weak authentication system, and very simple authorization .
  5. 5. INSTALLATION Step 1:- Download the latest production release of MongoDB Step 2:- Extract the downloaded archive. • In Windows Explorer, find the MongoDB download file, typically in the default Downloads directory. • Extract the archive to C: by right clicking on the archive and selecting Extract All and Step 3:- Move the MongoDB directory to another location. • cd • move C:mongodb-win32-* C:mongodb
  6. 6. INSTALLATION(Cont…) Step 4:- Set Up the Data Directory Step 5:- Start MongoDB The default location for the MongoDB data directory is C:datadb. Create this folder using the Command Prompt. Go to the C: directory and issue the following command sequence: md data md datadb You can specify an alternate path for data files using the C:mongodbbinmongod.exe --dbpath d:testmongodbdata C:mongodbbinmongod.exe This will start the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.
  7. 7. INSTALLATION(Cont…) Step 6:- Connect to MongoDB Connect to MongoDB using the mongo.exe shell. C:mongodbbinmongo.exe The mongo.exe shell will connect to mongod.exe running on the localhost interface and port 27017 by default.
  8. 8. BASIC OPERATIONS Oper 1:- Related to Database After starting the mongo shell your session will use the test database by default. • To show the name of current database -> DB • To display list of database -> show dbs • Switch to a new database named mydb or create new database -> use mydb NOTE:MongoDB will not permanently create a database until you insert data into that database.
  9. 9. BASIC OPERATIONS(Cont…) Oper 2:- Create a Collection and Insert Documents • MongoDB uses dynamic schemas , you also need not specify the structure of your documents before inserting them into the collection. • Insert documents in testDb collection db.testDb.insert({x: 20}) db.testDb.insert({x: 25 , name: “mongo”}) • When you insert the first document, the mongod will create both a mydb database and the testData collection. • All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.
  10. 10. BASIC OPERATIONS(Cont…) • To show list of collections in current database -> show collections • To show list of documents in collection -> db.testDb.find() • Query for Specific Documents -> db.testDb.find({x: 18}) • Limit the Number of Documents in the Result Set -> db.testDb.find().limit(3) Oper 3:- Update an existing document • In MongoDB, db.collection.update() and the methods perform update operations.
  11. 11. BASIC OPERATIONS(Cont…) •By default, the db.collection.update() method updates a single document. However, with the multi option, update() can update all documents in a collection that match a query. db.inventory.update( { type: "book", item : "journal" }, { $set : { qty: 10 } }, { upsert : true } ) •Call the update() method with the upsert flag to create a new document if no document matches the update’s query criteria.
  12. 12. BASIC OPERATIONS(Cont…) By default, db.collection.remove() method removes all documents that match its query. However, the method can accept a flag to limit the delete operation to a single document. Oper 4:- Delete an existing document In MongoDB, db.collection.remove() method performs delete operations.
  13. 13. Oper 5:- Fetching documents from collections BASIC OPERATIONS(Cont…)
  14. 14. BASIC OPERATIONS(Cont…) Specifying an equality condition –> db.inventory.find( { type: "snacks" } ) Specify Conditions Using Query Operators -> db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } ) Specify AND Conditions -> db.inventory.find( { type: 'food', price: { $lt: 9.95 } } ) Specify OR Conditions -> db.inventory.find({ $or: [{ qty: { $gt: 100 } }, { price: { $lt: 9.95 } }]})
  15. 15. BASIC OPERATIONS(Cont…)
  16. 16. BASIC TERMS • Queries in MongoDB return all fields in all matching documents by default. To limit the amount of data that MongoDB sends to applications, include a projection in the queries. 1:- Projection Exclude One Field From a Result Set db.records.find( { "user_id": { $lt: 42} }, { history: 0} ) NOTE : you cannot mix exclusive and inclusive projections , Except for excluding the _id field in inclusive projections. Return Two Fields and Exclude _id db.records.find( { "user_id": { $lt: 42} }, { "_id": 0, "name": 1 , "email": 1 } ) 2:- Cursors In the mongo shell, the primary method for the read operation is the db.collection.find() method. This method queries a collection and returns a cursor to the returning documents.
  17. 17. SQL to MongoDB Mapping Chart SQL Terms/Concepts MongoDB Terms/Concepts database database table collection row document or BSON document column field index index table joins embedded documents and linking primary key Specify any unique column or column combination as primary key. primary key In MongoDB, the primary key is automatically set to the_id field.
  18. 18. SQL to MongoDB Mapping Chart SQL Schema Statements MongoDB Schema Statements CREATE TABLE users ( id MEDIUMINT NOT NULL AUTO_INCREMENT, user_id Varchar(30), age Number, status char(1), PRIMARY KEY (id) ) Implicitly created on first insert() operation. The primary key _id is automatically added if _id field is not specified. db.users.insert( { user_id: "abc123", age: 55, status: "A" } ) However, you can also explicitly create a collection: db.createCollection("users") ALTER TABLE users ADD join_date DATETIME there is no structural alteration at the collection level. However, at the document level, update() operations can add fields to existing documents using the $set operator. 1:- Create and alter
  19. 19. SQL to MongoDB Mapping Chart SQL Schema Statements MongoDB Schema Statements ALTER TABLE users DROP COLUMN join_date at the document level, update() operations can remove fields from documents using the $unset operator. db.users.update( { }, { $unset: { join_date: "" } }, { multi: true } ) CREATE INDEX idx_user_id_asc_age_desc ON users(user_id, age DESC) db.users.ensureIndex( { user_id: 1, age: -1 } ) DROP TABLE users db.users.drop()
  20. 20. SQL to MongoDB Mapping Chart 2:- Insert SQL INSERT Statements MongoDB insert() Statements INSERT INTO users(user_id, age, status) VALUES ("bcd001", 45, "A") db.users.insert( { user_id: "bcd001", age: 45, status: "A" } )
  21. 21. SQL to MongoDB Mapping Chart 3:- Select SELECT user_id, status FROM users db.users.find( { }, { user_id: 1, status: 1, _id: 0 } ) SELECT * FROM users WHERE status != "A" db.users.find( { status: { $ne: "A" } } ) SELECT * FROM users WHERE status = "A" AND age = 50 db.users.find( { status: "A", age: 50 } ) SELECT * FROM users WHERE status = "A" OR age = 50 db.users.find( { $or: [ { status: "A" } , { age: 50 } ] } ) SELECT * FROM users WHERE age > 25 AND age <= 50 db.users.find( { age: { $gt: 25, $lte: 50 } } )
  22. 22. SQL to MongoDB Mapping Chart 3:- Select(Cont…) SELECT * FROM users WHERE user_id like "bc%" db.users.find( { user_id: /^bc/ } ) SELECT * FROM users WHERE status = "A" ORDER BY user_id DESC db.users.find( { status: "A" } ).sort( { user_id: -1 } ) SELECT COUNT(*) FROM users db.users.count() or db.users.find().count() SELECT COUNT(user_id) FROM users db.users.count( { user_id: { $exists: true } } ) or db.users.find( { user_id: { $exists: true } } ).count()
  23. 23. SQL to MongoDB Mapping Chart 3:- Select(Cont…) SELECT DISTINCT(status) FROM users db.users.distinct( "status" ) SELECT * FROM users LIMIT 1 db.users.findOne() or db.users.find().limit(1) SELECT * FROM users LIMIT 5 SKIP 10 db.users.find().limit(5).skip(10) EXPLAIN SELECT * FROM users WHERE status = "A" db.users.find( { status: "A" } ).explain()
  24. 24. SQL to MongoDB Mapping Chart 4:- Update records SQL Update Statements MongoDB update() Statements UPDATE users SET status = "C" WHERE age > 25 db.users.update( { age: { $gt: 25 } }, { $set: { status: "C" } }, { multi: true } ) UPDATE users SET age = age + 3 WHERE status = "A" db.users.update( { status: "A" } , { $inc: { age: 3 } }, { multi: true } )
  25. 25. SQL to MongoDB Mapping Chart 5:- Delete records SQL Delete Statements MongoDB remove() Statements DELETE FROM users WHERE status = "D" db.users.remove( { status: "D" } ) DELETE FROM users db.users.remove({})
  26. 26. THANK YOU FOR READING Dhaval M!5trY