Professional Documents
Culture Documents
Title:
MongoDB- Aggregate and Indexing:
Implement aggregation and indexing with suitable example using
MongoDB
Program:
db1 0.000GB
local 0.000GB
switched to db db1
> db.createCollection("student")
{ "ok" : 1 }
> show collections
Student
WriteResult({ "nInserted" : 1 })
> db.student.insert({"id":2, "Name": "Kartik", "Credits": 8.2})
WriteResult({ "nInserted" : 1 })
> db.student.insert({"id":3, "Name": "Sarvesh", "Credits": 7.5})
WriteResult({ "nInserted" : 1 })
> db.student.insert({"id":4, "Name": "Shweta", "Credits":8.9})
WriteResult({ "nInserted" : 1 })
> db.student.find()
{ "_id" : ObjectId("61adfee91d41af91142322fb"), "id" : 1, "Name" : "Vaishnavi", "Credits" : 7.9 }
{ "_id" : ObjectId("61adff301d41af91142322fc"), "id" : 2, "Name" : "Kartik", "Credits" : 8.2 }
Create Index
> db.student.createIndex({"id":1})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
Get Index
> db.student.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"id" : 1
},
"name" : "id_1"
}
]
Drop Index
> db.student.dropIndexes({"id":1})
{ "nIndexesWas" : 2, "ok" : 1 }
Aggregate Functions:
> db.product.insert([
... {item: "Paste", amount:40, customer:"Mike"},
... {item: "Milk", amount:30, customer:"Sam"},
... {item: "Bread", amount:20, customer:"Alice"},
... {item: "Pizza", amount:60, customer:"Mike"},
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 8,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.product.find()
1. Sum
> db.product.aggregate([{$group:{_id:"$customer", total: {$sum: "$amount"}}}])
{ "_id" : "Sam", "total" : 90 }
{ "_id" : "Alice", "total" : 50 }
2. Min
> db.product.aggregate([{$group:{_id:"$customer", total: {$min: "$amount"}}}])
{ "_id" : "Sam", "total" : 20 }
{ "_id" : "Alice", "total" : 20 }
3. Max
> db.product.aggregate([{$group:{_id:"$customer", total: {$max: "$amount"}}}])
{ "_id" : "Tom", "total" : 30 }
{ "_id" : "Mike", "total" : 60 }
4. First
> db.product.aggregate([{$group:{_id:"$customer", total: {$first: "$amount"}}}])
{ "_id" : "Tom", "total" : 30 }
{ "_id" : "Mike", "total" : 40 }
{ "_id" : "Alice", "total" : 20 }
5. Last
> db.product.aggregate([{$group:{_id:"$customer", total: {$last: "$amount"}}}])
{ "_id" : "Sam", "total" : 20 }
{ "_id" : "Alice", "total" : 30 }
{ "_id" : "Tom", "total" : 30 }
6. Avg
> db.product.aggregate([{$group:{_id:"$customer",total: {$avg: "$amount"}}}])
{ "_id" : "Sam", "total" : 30 }
{ "_id" : "Alice", "total" : 25 }
{ "_id" : "Tom", "total" : 30 }
7. Skip
> db.product.aggregate([{$match: {customer:"Mike"}},{$skip:1}]); { "_id" :
ObjectId("61ae17371d41af9114232302"), "item" : "Pizza", "amount" : 60, "customer" : "Mike" }
8. Limit
> db.product.aggregate([{$match: {customer:"Mike"}},{$limit:1}]);
{ "_id" : ObjectId("61ae17371d41af91142322ff"), "item" : "Paste", "amount" : 40, "customer" :
"Mike" }