xxxxxxxxxx
let videos= await Beg.aggregate([
{
$project: { // allows you to select or unselect filed.
_id: 1,//_id: 1 will select the field and _id: 0 will unselect field
},
},
{
$lookup: {
from: "videos", //the sub table or document
localField: "_id", // filed name of main table or doc
foreignField: "begId", // filed name of sub table or doc
as: "videos", // name your object
},
},
]);
xxxxxxxxxx
//routes/tourRouter.js
router.route('/tour-stats').get(tourController.getTourStats);
//controller/tourController.js
//NOTES::Aggregation pipeline to get tours stats
exports.getTourStats = async (req, res) => {
try {
const stats = await Tour.aggregate([
{
$match: { ratingsAverage: { $gte: 4.5 } },
},
{
$group: {
_id: { $toUpper: '$difficulty' },
num: { $sum: 1 },
numRatings: { $sum: '$ratingsQuantity' },
avgRating: { $avg: '$ratingsAverage' },
avgPrice: { $avg: '$price' },
minPrice: { $min: '$price' },
maxPrice: { $max: '$price' },
},
},
{
$sort: { avgPrice: 1 },
},
// { $match: { _id: { $ne: 'EASY' } } },
]);
res.status(200).json({
status: 'sucess',
results: stats.length,
data: stats,
});
} catch (error) {
console.log(error);
res.status(404).json({
status: 'fail',
message: error,
});
}
};
xxxxxxxxxx
const aggregate = Model.aggregate([
{ $project: { a: 1, b: 1 } },
{ $skip: 5 }
]);
Model.
aggregate([{ $match: { age: { $gte: 21 }}}]).
unwind('tags').
exec(callback);
xxxxxxxxxx
var followers_count = 30;
db.locations.find({
"$expr": {
"$and": [
{ "$eq": ["$name", "development"] },
{ "$gte": [{ "$size": "$followers" }, followers_count ]}
]
}
});
xxxxxxxxxx
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}