Skip to main content

Posts

Showing posts from December, 2015

$sort (aggregation) in MongoDB

$sort is responsible to sorting input document and returns it to pipeline. If you aware with relational Database like SQL server $sort work same as ORDER BY clause.

Syntax:

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort use to sort result in ascending or descending order according particular field(s). For ascending and descending we used following values.
1 for the ascending.-1 for descending
Example:
Suppose we have a collection named “myCollection “as below.

{ "uid" : 1, " BookTitle": "book1", "price" : 20, "quantity" : 1, "date" : ISODate("2016-08-05T07:00:00Z") } { "uid" : 2, " Book Title " : " book2", "price" : 10, "quantity" : 2, "date" : ISODate("2016-08-05T08:00:00Z") } { "uid" : 3, " Book Title " : " book3", "price" : 30, "quantity&quo…

$group (aggregation) in MongoDB

IF we want to group document by specific expression and want to output for each distinct grouping of document here we have to use $group. IF you familiar with Relational Database like SQL Server, It's work same like GROUP BY clause.
Output document contains the _id field which contains the distinct group by key also output document contains computed fields which grasp the value of some accumulator expression grouped by the _id.
Syntax:

{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... }

Accumulator Operator:
$num : It's returns sum of the numeric value. It can be use in $project also in mongodb 3.2 version.
$avg  : It's returns the average of numeric values. It can be use in $project also in mongodb 3.2 version.
$first : It's returns a value from the first document for each group.
$last : It's returns a value from the first document for each group.
$max : It's returns the highest expression value for each group.…