Last active
August 18, 2022 02:57
-
-
Save alexanderankin/ead7b451224f646567001b6fbee42733 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { MongoClient } from "mongodb"; | |
| const uri = "mongodb://localhost"; | |
| async function insertSampleData() { | |
| const client = new MongoClient(uri); | |
| try { | |
| const database = client.db("tj08-17-22"); | |
| const saleCollection = database.collection("sale"); | |
| const documents = [ | |
| { name: 'apple', createdAt: new Date('2022-08-11T02:10:11.000Z'), p: [{ id: 1, q: 1 }, { id: 3, q: 11 }], totalPrice: 1, }, | |
| { name: 'apple', createdAt: new Date('2022-08-12T02:10:11.000Z'), p: [{ id: 2, q: 2 }, { id: 2, q: 12 }], totalPrice: 9, }, | |
| { name: 'apple', createdAt: new Date('2022-08-13T02:10:11.000Z'), p: [{ id: 3, q: 3 }, { id: 3, q: 13 }], totalPrice: 3, }, | |
| { name: 'pear', createdAt: new Date('2022-08-14T02:10:11.000Z'), p: [{ id: 2, q: 4 },], totalPrice: 4, }, | |
| { name: 'pear', createdAt: new Date('2022-08-15T02:10:11.000Z'), p: [{ id: 2, q: 5 },], totalPrice: 1, }, | |
| { name: 'pear', createdAt: new Date('2022-08-16T02:10:11.000Z'), p: [{ id: 2, q: 6 },], totalPrice: 5, }, | |
| { name: 'fruit', createdAt: new Date('2022-08-17T02:10:11.000Z'), p: [{ id: 1, q: 7 },], totalPrice: 2, }, | |
| ]; | |
| await saleCollection.deleteMany({}); | |
| const result = await saleCollection.insertMany(documents); | |
| console.log(`Data inserted: ${result.insertedCount}`); | |
| } finally { | |
| await client.close(); | |
| } | |
| } | |
| // insertSampleData().catch(console.dir); | |
| async function find() { | |
| const client = new MongoClient(uri); | |
| try { | |
| const database = client.db("tj08-17-22"); | |
| const saleCollection = database.collection("sale"); | |
| let result = await saleCollection.aggregate([ | |
| // { $match: { createdAt: { $gte: new Date('2022-08-13'), $lt: new Date('2022-08-15') } } }, | |
| // { $group: { _id: "$name", sumValue: { $sum: '$totalPrice', } } } | |
| { $unwind: '$p' }, | |
| { $group: { _id: "$p.id", sumValue: { $sum: '$p.q', } } } | |
| ]); | |
| await result.forEach(console.log); | |
| } finally { | |
| { | |
| await client.close(); | |
| } | |
| } | |
| } | |
| insertSampleData().then(find).catch(console.dir); | |
| // find().catch(console.dir); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment