@rollin
To implement the aggregate method on MongoDB, you can use the following steps:
Here is an example of how to implement the aggregate method on MongoDB:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Connect to the MongoDB database const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'mydb'; MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => { if (err) throw err; const db = client.db(dbName); // Define the pipeline stages const pipeline = [ { $match: { status: 'active' } }, { $group: { _id: '$category', total: { $sum: '$quantity' } } }, { $sort: { total: -1 } } ]; // Apply the aggregation pipeline db.collection('products').aggregate(pipeline).toArray((err, result) => { if (err) throw err; console.log(result); client.close(); }); }); |
In this example, the code connects to a MongoDB database, defines a pipeline with three stages (matching active products, grouping by category and summing quantities, and sorting by total), and applies the pipeline using the aggregate
method on the products
collection. The result is then logged to the console.
You can customize the pipeline stages according to your specific requirements to process the documents in the collection and retrieve the desired output.