Thursday 5 January 2023

Mongo Commands

Basic commands in Mongo:

1)use dbname: is used to select specific database that need to be used. If no database is present , it will create new db.
2)show collections : is used to list all collection in db.
3)db.collectionName.find({}). : is used to list all documents in specific collection.
4)db.collectionName.countDocuments({}) ::  returns number of documents present in collection.
5)db.collectionName.find().sort({"date":-1}) :: sort by date in descending order .
6)db.collectionName.find().sort({"date":1}) :: sort by date in ascending order.
7)db.collectionName.deleteMany({}) :: delete all documents in collection
8)db.collectionName.deleteOne({}) :: 
9) db. collectionName .insertMany():  will create collection if does not exist with multiple insert.
10)aggregation examples: we can use aggregation whenever we want to aggregate data. Mongo supports aggregation using pipeline wherein pipeline consists of different stages. Each stage can do different task like filtering, matching , sorting on the selected set of documents. I feel like aggregation is important so putting some examples for reference. 


10.1) created demo collection with multiple records.

db.demo.insertMany([{
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T10:00:00.000Z"
}, {
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T11:00:00.000Z"
}, {
"tid": 1,
"sq": 2,
"state": "assigned",
"date": "2023-05-25T12:00:00.000Z"
}, {
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T12:00:00.000Z"
}, {
"tid": 1,
"sq": 2,
"state": "assigned",
"date": "2023-05-25T13:00:00.000Z"
}, {
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T14:00:00.000Z"
}, {
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T15:00:00.000Z"
}])



10.2)  Perform aggregation while using some options supported by aggregate function.


db.demo.aggregate([{
"$match": {
"state": "assigned",
"date": {
"$gte": "2023-05-25T10:00:00.000Z",
"$lte": "2023-05-26T10:00:00.000Z"
}
}
}, {
"$sort": {
"date": 1
}
}, {
"$group": {
"_id": {
"state": "$state",
"sq": "$sq",
"ticketId": "$tid"
},
"firstdate": {
"$first": "$date"
},
"lastdate": {
"$last": "$date"
},
"doc": {
"$first": "$$ROOT"
}
}
}])


10.3) Query result will be as follows: 

{
"_id": {
"state": "assigned",
"sq": 2,
"ticketId": 1
},
"firstdate": "2023-05-25T12:00:00.000Z",
"lastdate": "2023-05-25T13:00:00.000Z",
"doc": {
"_id": ObjectId("646fbf7fada80b4697d958a5"),
"tid": 1,
"sq": 2,
"state": "assigned",
"date": "2023-05-25T12:00:00.000Z"
}
} {
"_id": {
"state": "assigned",
"sq": 1,
"ticketId": 1
},
"firstdate": "2023-05-25T10:00:00.000Z",
"lastdate": "2023-05-25T15:00:00.000Z",
"doc": {
"_id": ObjectId("646fbf7fada80b4697d958a3"),
"tid": 1,
"sq": 1,
"state": "assigned",
"date": "2023-05-25T10:00:00.000Z"
}
}





9) aggregate pipeline