Wednesday, 11 November 2015

MongoDB - CRUD operations

 The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection.

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
Options like- capped, autoIndexID, size, max

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

Examples:

Basic syntax of createCollection() method without options is as follows
>use krishnamongodb
switched to db krishnamongodb
>db.createCollection("homecollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections
>show collections
homecollection
system.indexes
 
Following example shows the syntax of createCollection() method with few important options:
>db.createCollection("homecol", { capped : true, autoIndexID : true, size : 3142800, max : 10000 } )
{ "ok" : 1 }
>
 

 
NOTE: 
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
>db.homecollection.insert({"name" : "Krishna Kumar"})
>show collections
homecol
homecollection
system.indexes
>
 

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.
Syntax:

Basic syntax of drop() command is as follows -

db.COLLECTION_NAME.drop()



Method - insert()

To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method.

Syntax

Basic syntax of insert() command is as follows:
>db.COLLECTION_NAME.insert(document)

Example

>db.hcomecol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is NOSql database',
   by: 'Krishna Kumar Chourasiya',
   url: 'http://mongodbworkspace.blogspot.in/',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 1000
})
 
Here homecol is our collection name, as created in previous tutorial. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert document into it.
In the inserted document if we don't specify the _id parameter, then MongoDB assigns an unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
To insert multiple documents in single query, you can pass an array of documents in insert() command.

NOTE

To insert the document you can use db.homecol.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.

Insert Boolean Data

While inserting boolean data, you need to make sure you are using proper boolean keywords like (true,false). It should always start from lower case not from capital case.

Example: 
db.UserCredential.insert({"flag":true}) WriteResult({ "nInserted" : 1 }) db.UserCredential.insert({"flag":false}) WriteResult({ "nInserted" : 1 })

Method - delete()

MongoDB's remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
  1. Deletion Criteria : (Optional) deletion criteria according to documents will be removed.
  2. justOne : (Optional) if set to true or 1, then remove only one document.

Syntax:

Basic syntax of remove() method is as follows
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)


Save Vs Update

MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB - Update()

The update() method updates values in the existing document.

Syntax:

Basic syntax of update() method is as follows
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

MongoDB - Save()

The save() method replaces the existing document with the new document passed in save() method

Syntax

Basic syntax of mongodb save() method is shown below:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})



How to avoid Duplicate Entry

To avoid duplicate entries in mongodb, Use an index with the {unique:true} option.
MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.


 For Example - 
db.homeCollections.ensureIndex({name:1},{unique:true});


If you wish for null values to be ignored from the unique key, then you have to also make the index sparse, by also adding the sparse option:

For Example - 

db.users.ensureIndex({email:1},{unique:true, sparse:true});

No comments:

Post a Comment

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...