0% found this document useful (0 votes)
56 views19 pages

Assingment Group B17

This document discusses various MongoDB indexing, querying, and data manipulation methods including: 1. Indexing in MongoDB uses indexes to improve query performance by storing a portion of data in an easy to traverse form. The ensureIndex() method is used to create indexes. 2. Common MongoDB methods include find() to query, insert() to add, update() to modify, remove() to delete documents, and aggregation framework for data analysis. 3. Criteria like $or, $and can be used to perform logical OR and AND queries on document fields. Indexes further optimize query performance.

Uploaded by

mayank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views19 pages

Assingment Group B17

This document discusses various MongoDB indexing, querying, and data manipulation methods including: 1. Indexing in MongoDB uses indexes to improve query performance by storing a portion of data in an easy to traverse form. The ensureIndex() method is used to create indexes. 2. Common MongoDB methods include find() to query, insert() to add, update() to modify, remove() to delete documents, and aggregation framework for data analysis. 3. Criteria like $or, $and can be used to perform logical OR and AND queries on document fields. Indexes further optimize query performance.

Uploaded by

mayank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Experiment No: Group B(17)

Title: Indexing and Querying with MongoDB.


Aim: Indexing and querying with MongoDB using suitable example.
Prerequisites: Basic of MongoDB.
Objectives: Ability of problem solving using advanced databases
techniques and
tools
Theory:
MongoDB Indexing:
Indexes support the efficient resolution of queries. Without indexes,
MongoDB must scan every document of a collection to select those
documents that match the query statement. This scan is highly inefficient
and require the mongod to process a large volume of data.
Indexes are special data structures, that store a small portion of the
data set in an easy to traverse form. The index stores the value of a
specific field or set of fields, ordered by the value of the field as specified
in index.
The ensureIndex() Method:
To create an index you need to use ensureIndex() method of
mongodb.
Syntax:
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of filed on which you want to create index and
1 is for ascending order. To create index in descending order you need to
use -1.
ensureIndex() method also accepts list of options (which are
optional), whose list is given below:
Paramet
er
Type

Description
Builds the index in the background so that building
an
backgrou
index does not block other database activities.
Boolean Specify true
nd
to build in the background. The default value is
false.
Creates a unique index so that the collection will not
accept
unique
Boolean insertion of documents where the index key or keys

match
an existing value in the index. Specify true to create
a
unique index. The default value is false.

>db.mycol.ensureIndex({"title":1})
In ensureIndex() method you can pass multiple fields, to create
index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
MongoDB Commands:
1. use Command:
MongoDB use DATABASE_NAME is used to create database. The
command will create a new database, if it doesn't exist otherwise it will
return the existing database.
Syntax:
use DATABASE_NAME
Example:
If you want to create a database with name <mydb>, then use
DATABASE statement would be as follows:
>use mydb
switched to db mydb
To check your currently selected database use the command db
>db
my
db
If you want to check your databases list, then use the command
show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display
database you need to insert atleast one document into it.
>db.movie.insert({"name":"MandarM"
})
>show dbs
0.78125G
local B
0.23012
mydb
GB
test 0.23012GB
In mongodb default database is test. If you didn't create any
database then collections will be stored in test database.
2. The dropDatabase() Method:
MongoDB db.dropDatabase() command is used to drop a existing

database.
Syntax:
db.dropDatabase()

This will delete the selected database. If you have not selected any
database,
then it will delete default 'test' database
Example:
First, check the list available databases by using the command
show dbs
>show dbs
local

0.78125GB

mydb
test

0.23012GB
0.23012GB

>

If you want to delete new database <mydb>, then


dropDatabase() command would be as follows:
>use mydb
switched to
db mydb
>db.dropDat
abase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases
>show dbs
local
0.78125GB
test
0.23012GB
>

3. The createCollection() Method:


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

Paramet
er
Type

Description

Name

String

Name of the collection to be created

Options

(Optional) Specify options about memory size and


Document indexing

Examples:
Basic syntax of createCollection() method without options is as
follows
>use test
switched to
db test

>db.createCollection("mycollection")
{ "ok" : 1 }
>

You can check the created collection by using the command show
collections
>show
collections
mycollection
In mongodb you don't need to create collection. MongoDB creates
collection automatically, when you insert some document.
>db.
mandar.insert({"name":"MandarMokash
i "}) >show collections

mycol
mycollection
system.index
es Mandar
>

4. The drop() Method:


MongoDB's db.collection.drop() is used to drop a collection from the
database.
Syntax:
db.COLLECTION_NAME.drop()
Example:
First, check the available collections into your database mydb

>use mydb
switched to db
mydb >show
collections mycol
mycollection
system.index
es
MandarMoka
shi
>
Now drop the collection with the name
mycollection >db.mycollection.drop()
true
>
Again check the list of collections into database
>show
collections
mycol

system.indexes
MandarMokashi
>
5. The insert() Method:
To insert data into MongoDB collection, you need to use MongoDB's
insert() or save()method.
Syntax
>db.COLLECTION_NAME.insert(document
) Example

>db.mycol.insert({
_id:
ObjectId(7df78ad8902c),
title: 'MongoDB
Overview',

description: 'MongoDB is no sql


database', by: MandarMokashi,
url:

'http://www.dypic.in',

tags:

['mongodb', 'database', 'NoSQL'],


likes: 100
})
Here mycol 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.
Example
>db.post.insert([

{
title: 'MongoDB Overview',
description: 'MongoDB is no sql
database', by: MandarMokashi,
url:

'http://www.dypic.in',

tags:

['mongodb', 'database', 'NoSQL'],


likes: 100
},

{
title: 'NoSQL Database',
description: 'NoSQL database doesn't have
tables', by: MandarMokashi,
url:

'http://www.dypic.in',

tags:

['mongodb', 'database', 'NoSQL'],


likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new
Date(2013,11,10,2,35), like: 0
}
]
}
])

6. The find() Method


To query data from MongoDB collection, you need to use MongoDB's
find() method.
Syntax
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non structured
way.
7. The pretty() Method
To display the results in a formatted way, you can use pretty()
method.

Syntax:
>db.mycol.find().pretty()
Example
>db.mycol.find().pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql
database", "by": "MandarKorade",
"url": "http://www.dypic.in", "tags":
["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

8. OR in
MongoDB
Syntax:
To query documents based on the OR condition, you need to use
$or keyword.
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()

Example
Below given example will show all the tutorials written by
MandarMokashi or whose title is 'MongoDB Overview'
>db.mycol.find({$or:[{"by":"MandarKorade"},{"title": "MongoDB
Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql
database", "by": "MandarKorade",
"url": "http://www.dypic.in", "tags":
["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

9. Using AND and OR


together Example
Below given example will show the documents that have likes
greater than 100 and whose title is either 'MongoDB Overview' or by is
MandarMokashi. Equivalent sql where clause is 'where likes>10 AND
(by = MandarMokashi OR title
= 'MongoDB Overview')'
>db.mycol.find("likes": {$gt:10}, $or: [{"by": "MandarKorade"}, {"title":
"MongoDB Overview"}] }).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",

"by": "MandarKorade",
"url": "http://www.dypic.in", "tags":
["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

10. MongoDB Update() method


The update() method updates values in the existing document.
Syntax:
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Consider the mycol collectioin has following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}

"_id"

ObjectId(5983548781331adf45ec6),

"title":"NoSQL Overview"}

{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

Following example will set the new title 'New MongoDB Tutorial' of
the documents whose title is 'MongoDB Overview'
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New
MongoDB Tutorial'}})
>db.mycol.find()
{

"_id"

ObjectId(5983548781331adf45ec5),

"title":"New

MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6),


"title":"NoSQL Overview"}
{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

>
By default mongodb will update only single document, to update
multiple you need to set a paramter 'multi' to true.

>db.mycol.update({'title':'MongoDB
{'title':'NewMongoDB

Overview'},{$set:

Tutorial'}},{multi:true})
11.

The remove() Method:

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:
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Consider the mycol collectioin has following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}

"_id"

ObjectId(5983548781331adf45ec6),

"title":"NoSQL Overview"}

{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

Following example will remove all the documents whose title is


'MongoDB
Overview'
Remove only one
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

>

If there are multiple records and you want to delete only first record,
then set justOne parameter in remove() method
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Remove All documents
If you don't specify deletion criteria, then mongodb will delete whole
documents from the collection. This is equivalent of SQL's truncate
command.
>db.mycol.remove()
>db.mycol.find()
>

12. The find() Method


MongoDB's find() method, explained in MongoDB Query Document
accepts second optional parameter that is list of fields that you want to
retrieve. In MongoDB when you execute find() method, then it displays all
fields of a document. To limit this you need to set list of fields with value 1
or 0. 1 is used to show the filed while 0 is used to hide the field.
Syntax:
>db.COLLECTION_NAME.find({},{KEY:1})
Example
Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}

"_id"

ObjectId(5983548781331adf45ec6),

"title":"NoSQL Overview"}

"_id"

"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

Following example will display the title of the document while


quering the document.
>db.mycol.find({},
{"title":1,_id:0})
{"title":"MongoDB
Overview"} {"title":"NoSQL
Overview"}
{"title":"MandarKoradeOverv
iew"}
>

Please note _id field is always displayed while executing find()


method, if you don't want this field, then you need to set it as 0
13. The sort() Method
To sort documents in MongoDB, you need to use sort() method.
sort() method accepts a document containing list of fields along with
their sorting order. To specify sorting order 1 and -1 are used. 1 is used for
ascending order while -1 is used for descending order.
Syntax:
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}

"_id"

ObjectId(5983548781331adf45ec6),

"title":"NoSQL Overview"}

{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

Following example will display the documents sorted by title in


descending
order.
>db.mycol.find({},
{"title":1,_id:0}).sort({"title":-1})
{"title":"MandarKoradeOverview"}
{"title":"NoSQL Overview"}

{"title":"MongoDB Overview"}
>
Please note if you don't specify the sorting preference, then sort()
method will display documents in ascending order.
14. The Limit() Method
To limit the records in MongoDB, you need to use limit() method.
limit() method accepts one number type argument, which is number of
documents that you want to displayed.
Syntax:
>db.COLLECTION_NAME.find().limit(NUMBER)
Example
Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB
Overview"}

"_id"

ObjectId(5983548781331adf45ec6),

"title":"NoSQL Overview"}

{
"_id"
:
"title":"MandarKoradeOverview"}

ObjectId(5983548781331adf45ec7),

Following example will display only 2 documents while quering the


document.
>db.mycol.find({},
{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>

If you don't specify number argument in limit() method then it will


display all documents from the collection.

15. MongoDB Skip() Method


Apart from limit() method there is one more method skip() which
also accepts number type argument and used to skip number of
documents.
Syntax:
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Example:
Following example will only display only second document.
>db.mycol.find({},
{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}

>

Please note default value in skip() method is 0

Conclusion:
Here we performed Indexing and querying with MongoDB using
suitable example.

You might also like