Mongodb-Aggregation-And-Indexing Group-B-Assignment-15batch-1
Mongodb-Aggregation-And-Indexing Group-B-Assignment-15batch-1
>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.
EXAMPLE
>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})
>
ensureIndex() method also accepts list of options (which are optional), whose list is given
below:
For a text index, the language that determines the list of stop
default_language string words and the rules for the stemmer and tokenizer. The
default value isenglish.
1.2.2 AGGREGATION
Aggregations operations process data records and return computed results. Aggregation
operations group values from multiple documents together, and can perform a variety of
operations on the grouped data to return a single result. In sql count(*) and with group by
is an equivalent of MongoDB aggregation.
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
EXAMPLE:
In the collection you have the following data:
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10
},
{
_id: ObjectId(7df78ad8902e)
Now from the above collection if you want to display a list that how many tutorials are
written by each user then you will use aggregate() method as shown below:
SQL equivalent query for the above use case will be select by_user, count(*) from mycol
group by by_user
In the above example we have grouped documents by field by_user and on each occurance
of by_user previous value of sum is incremented. There is a list available aggregation
expression.
db.mycol.aggregate([{$group : {_id :
Sums up the defined value from all
$sum "$by_user", num_tutorial : {$sum :
documents in the collection.
"$likes"}}}])
have individual documents again. Thus with this stage we will increase the amount
of documents for the next stage.
Assignment Question:
1. Explain Types of Index in MongoDB
2. Explain Pipeline Concept in Mogo DB