mongodbAggregation

https://learn.mongodb.com/learn/course/mongodb-aggregation/lesson-1-introduction-to-mongodb-aggregation/learn?page=2 

Aggregation operations process multiple documents and return computed results. You can use aggregation operations to:

  • Group values from multiple documents together.

  • Perform operations on the grouped data to return a single result.

  • Analyze data changes over time.

To perform aggregation operations, you can use:

The command to use Aggregation is:
db.collecationname.aggregate(pipeline,options)

Pipeline:
A sequence of data aggregation opeartions or stages
Pipeline is an array
filtered grouped sorted transformed

$match:
filters data that matches criteria
$Group:
Groups documents based on criteria
$sort:
puts the document in specified order 1:ascending -1 :descending.. 

$out: writes the document that are returned by an aggregation pipeline into a collection

it crates new collection if not otherwise overwrites 

Options:
Documents can be passed  as well
valid  Aggregate stages:
$count
$group
$limit 
$lookup
$match
$merge
$sort
$project
$unwind
$unset
.............

1:

var pipeline=[
    {$sort:{"rollno":1}},
    
];
db.record.aggregate(pipeline);

2:
var pipeline=[
    {$sort:{"rollno":1}},
    {$limit:2}
];
db.record.aggregate(pipeline);

3:
var pipeline=[
{$set:{
  username:{$concat:["$name","$address"]}
}},
    {$sort:{"rollno":-1}}
    
];
db.record.aggregate(pipeline);




.........................................................................................
db.records.insertMany([
    {name:'rahul',city:'delhi',zone:'north'},
    {name:'raj',city:'delhi',zone:'south'},
    {name:'rakesh',city:'delhi',zone:'north'},
    {name:'akshay',city:'delhi',zone:'north'},
    {name:'suman',city:'up',zone:'north'}
])

.................................................................
1:matches the city delhi

var pipeline=[
{$match:{
"city":"delhi"  
  }

}
    
];
db.records.aggregate(pipeline);
2:

var pipeline=[
{$match:{
"city":"delhi"  
  }},
{$group:{
    _id:"$zone",
    name:{$count:{}}
}}
    
];
db.records.aggregate(pipeline);
..............................................

3.
var pipeline=[
{$project:{
name:1,
zone:1,
"state":"$city"  
  }}

    
];
db.records.aggregate(pipeline);
4.
var pipeline=[
{$count:"name" 
  }

    
];
db.records.aggregate(pipeline);

5...

var pipeline=[
{$count:"name" 
  },
{$out:"totalname"}
    
];
db.records.aggregate(pipeline);

Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation