Created
November 26, 2021 03:46
-
-
Save shramee/f8ecab25484234f79798cdab0ca10ca3 to your computer and use it in GitHub Desktop.
NTU SDI 4.3: Mongo DB aggregation pipelines with restaurants sample data
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
// region Setup database client | |
const { MongoClient } = require( 'mongodb' ); | |
// Server to connect to | |
const uri = "mongodb://localhost:27017"; | |
const dbServer = new MongoClient( uri ); | |
// endregion Setup database client | |
// region Connect to the database and test querying | |
(async () => { | |
await dbServer.connect(); | |
const db = dbServer.db( 'sample_restaurants' ); | |
const restaurants = db.collection( 'restaurants' ); | |
console.log( '\n-----------------------------------------------\n' ); | |
// region $match and $project demo | |
const pipeline = [ | |
// $match address.zipcode => 10466, cuisine => Chinese | |
{ $match: { "address.zipcode": "10466", "cuisine": "Chinese" } }, | |
// $project name to restaurant_name | |
{ $project: { restaurant_name: '$name', _id: false } }, | |
{$limit: 10}, | |
]; | |
const restaurantDocs = await restaurants.aggregate( pipeline ).toArray(); | |
console.log( 'Chinese restaurants in 10466: \n', restaurantDocs ); | |
// endregion $match and $project demo | |
console.log( '\n-----------------------------------------------\n' ); | |
// region $group demo | |
const groupPipeline = [ | |
// Find number of restaurants by cuisine | |
{ $group: { _id: '$cuisine', noOfOccurences: { $count: {} } } }, | |
// Additional feature, order cuisines by popularity | |
{ $sort: { noOfOccurences: -1 } }, | |
// Top five most popular cuisines in our database | |
{$limit: 5} | |
]; | |
const cousineCount = await restaurants.aggregate( groupPipeline ).toArray(); | |
console.log( 'Restaurant count by cuisine: \n', cousineCount ); | |
// endregion $group demo | |
console.log( '\n-----------------------------------------------\n' ); | |
// region $sort demo | |
// Get first 10 alphabetically arranged restaurants | |
const first10Pipeline = [ | |
// Filter out empty name docs | |
{ $match: { 'name': {$ne: ''} } }, | |
// Sort by name | |
{ $sort: { 'name': 1 } }, | |
// Limit to 10 results | |
{ $limit: 10 }, | |
// Project restaurants name | |
{ $project: { 'restaurant_name': '$name', _id: 0 } } | |
]; | |
const first10RestaurantDocs = await restaurants.aggregate( first10Pipeline ).toArray(); | |
console.log( 'First 10 sorted restaurants: \n', first10RestaurantDocs ); | |
// endregion $sort demo | |
})(); | |
// endregion Connect to the database and test querying |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment