tempCodeRunnerFile.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* global use, db */
  2. // MongoDB Playground
  3. // To disable this template go to Settings | MongoDB | Use Default Template For Playground.
  4. // Make sure you are connected to enable completions and to be able to run a playground.
  5. // Use Ctrl+Space inside a snippet or a string literal to trigger completions.
  6. // The result of the last command run in a playground is shown on the results panel.
  7. // By default the first 20 documents will be returned with a cursor.
  8. // Use 'console.log()' to print to the debug output.
  9. // For more documentation on playgrounds please refer to
  10. // https://www.mongodb.com/docs/mongodb-vscode/playgrounds/
  11. // Select the database to use.
  12. use('mongodbVSCodePlaygroundDB');
  13. // Insert a few documents into the sales collection.
  14. db.getCollection('sales').insertMany([
  15. { 'item': 'abc', 'price': 10, 'quantity': 2, 'date': new Date('2014-03-01T08:00:00Z') },
  16. { 'item': 'jkl', 'price': 20, 'quantity': 1, 'date': new Date('2014-03-01T09:00:00Z') },
  17. { 'item': 'xyz', 'price': 5, 'quantity': 10, 'date': new Date('2014-03-15T09:00:00Z') },
  18. { 'item': 'xyz', 'price': 5, 'quantity': 20, 'date': new Date('2014-04-04T11:21:39.736Z') },
  19. { 'item': 'abc', 'price': 10, 'quantity': 10, 'date': new Date('2014-04-04T21:23:13.331Z') },
  20. { 'item': 'def', 'price': 7.5, 'quantity': 5, 'date': new Date('2015-06-04T05:08:13Z') },
  21. { 'item': 'def', 'price': 7.5, 'quantity': 10, 'date': new Date('2015-09-10T08:43:00Z') },
  22. { 'item': 'abc', 'price': 10, 'quantity': 5, 'date': new Date('2016-02-06T20:20:13Z') },
  23. ]);
  24. // Run a find command to view items sold on April 4th, 2014.
  25. const salesOnApril4th = db.getCollection('sales').find({
  26. date: { $gte: new Date('2014-04-04'), $lt: new Date('2014-04-05') }
  27. }).count();
  28. // Print a message to the output window.
  29. console.log(`${salesOnApril4th} sales occurred in 2014.`);
  30. // Here we run an aggregation and open a cursor to the results.
  31. // Use '.toArray()' to exhaust the cursor to return the whole result set.
  32. // You can use '.hasNext()/.next()' to iterate through the cursor page by page.
  33. db.getCollection('sales').aggregate([
  34. // Find all of the sales that occurred in 2014.
  35. { $match: { date: { $gte: new Date('2014-01-01'), $lt: new Date('2015-01-01') } } },
  36. // Group the total sales for each product.
  37. { $group: { _id: '$item', totalSaleAmount: { $sum: { $multiply: [ '$price', '$quantity' ] } } } }
  38. ]);