.aggregate mongodb code example
Example 1: mongodb aggregate group
#equivalent of the following SQL instruction:
# SELECT COUNT(*) FROM Table
# GROUP BY your_field
query = db.collection.aggregate([
{
"$group": {
"_id": "$your_field", #GROUP BY your_field
"total": {"$sum":1} #COUNT(*)
}
}
])
Example 2: how to write the aggragation in mongodb
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "tutorials point", "num_tutorial" : 2 }
{ "_id" : "Neo4j", "num_tutorial" : 1 }
>
Example 3: MONGODB AGGREGATION tutorials
db.stocks.insertMany([
{ name: "Infosys", qty: 100, price: 800 },
{ name: "TCS", qty: 100, price: 2000 },
{ name: "Wipro", qty: 2500, price: 300 }
])
Example 4: how to use mongoose aggregate
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}
Example 5: how to use mongoose aggregate
new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);