If i have this schema
food = {
name : String,
favouriteFoods : []
}
and each favoritefood element is an object like so
var favoritefood = new Object;
favoritefood.cuisine = 'indian';
favoritefood.flavor = 'spicy';
is it possible to query mongoose to get all favoritefood objects have their flavor attribute set to 'spicy'?
You need to perform an aggregate
operation to get all the spicy favouirite foods grouped by name.
Match
all the food items, having at least one spicy favorite food. Unwind
the favorite food array. Match
all the unwinded favorite foods which are spicy. Group
by the food name. Project
them. The Code:
Food.aggregate([
{$match:{"favouriteFoods.flavor":"spicy"}},
{$unwind:"$favouriteFoods"},
{$match:{"favouriteFoods.flavor":"spicy"}},
{$group:{"_id":"$name","spicyFoods":{$push:"$favouriteFoods"}},
{$project:{"_id":0,"name":"$_id","spicyFoods":1}}
],function(err,res){
// console.log(res);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.