Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Last active July 20, 2016 08:05
Show Gist options
  • Select an option

  • Save OzieWest/ef767c863dfa136e1628c3f965e1055f to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/ef767c863dfa136e1628c3f965e1055f to your computer and use it in GitHub Desktop.
mongodb_native_query.js
// Пример ниже верен только для нативного монго драйвера - https://mongodb.github.io/node-mongodb-native
let cityId = <CITY_ID_HERE>;
let query = [
{
// найти город такой то
$match: { id: cityId }
},
{
// найти соответствующий ему регион
$lookup: { from: 'region', foreignField: 'id', as: 'region', localField: 'regionId' }
},
{
// “распаковать” регион - если этого не сделать то поле region будет массивом
$unwind: '$region'
},
{
$lookup: { from: 'type', foreignField: 'id', as: 'type', localField: 'typeId' }
},
{
// “распаковать” type - если этого не сделать то поле type будет массивом
$unwind: '$type'
},
{
// сформировать результирующий json
$project: {
id: 1,
name: 1,
region: { name: 1 },
type: { name: 1 }
}
}
];
// db - Это объект базы данных, как его получить в вашем фреймворке - гуглите
db.collection("city").aggregate(query, (err, results) => {
console.log(err, results)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment