Skip to content

Instantly share code, notes, and snippets.

@sushant-at-nitor
Created August 24, 2022 03:36
Show Gist options
  • Save sushant-at-nitor/12b10c9176f5b3337c1865df616b1920 to your computer and use it in GitHub Desktop.
Save sushant-at-nitor/12b10c9176f5b3337c1865df616b1920 to your computer and use it in GitHub Desktop.
MongoDB / Mongo aggregate example - mapReduce, aggregate query
db.getCollection('routes').aggregate([
{
$match: {city: 'Pune', transport: 'subway'}
},
{
$project: {emit: {key: {city: '$city', transport: '$transport'}, features: '$featureCollection.features'}}
},
{
$group: {
_id: "$emit.key",
routes: {
$accumulator: {
init: function() { return []; },
accumulate: function(state, value) { return Object.assign([], state, value); },
accumulateArgs: [ "$emit.features" ],
merge: function(state1, state2) { return Object.assign([], state1, state2); },
finalize: function(state) {
return state.filter(function(item){ return item.properties.type === 'relation' })
.map(function(item){
return {
id: item.properties.id,
name: item.properties.tags.name,
from: item.properties.tags.from,
to: item.properties.tags.to,
network: item.properties.tags.network,
operator: item.properties.tags.operator,
geometry: item.geometry,
stops: state.filter(function(stop){
return stop.properties.type === 'node' && stop.properties.relations.find(function(relation){
return relation.rel === item.properties.id;
})
}).map(function(stop){
return {
id: stop.properties.id,
name: stop.properties.tags.name,
location: stop.geometry,
}
})
}
})
}
}
}
}
}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment