如何使用聚合和展开返回文档和子数组?

时间:2017-03-26 20:26:46

标签: javascript node.js mongodb mongoose

我使用以下mongoose查询从文档中返回最受欢迎的零食。以下是文件:

{
  "_id": ObjectId("58d7d2d760b78902f1df3fa2"),
  "user_id": ObjectId("58d2dd4c8207c28149dbc748"),
  "calories": 2000,
  "date": 20170226,
  "snacks": [
{
  "nutrients": {
    "protein": 7.5,
    "carbs": 56.5,
    "fat": 10.5
  },
  "servings": 23.8,
  "calories": 526,
  "name": "Dairy milk"
},
"dinner": [ ],
"lunch": [ ],
"breakfast": [ ]
}

然后我使用以下查询:

user_food.aggregate({$unwind: $snacks},{$sortByCount: $snacks.name},function(err, results){
        if(err){
            console.log("something went wrong: " + err);
            return res.status(500).send(err);
        }
        else{
            return res.status(200).send(results);
        }
    });

返回:

_id:"Dairy milk"
count:3

我需要返回的是整个对象:

"nutrients": {
"protein": 7.5,
"carbs": 56.5,
"fat": 10.5
},
"servings": 23.8,
"calories": 526,
"name": "Dairy milk",
count:3

1 个答案:

答案 0 :(得分:0)

$sortByCount相当于$group + _id $sort。要在$group阶段添加更多字段,您需要使用$first获取指定字段的第一个值:

user_food.aggregate([{
    $unwind: "$snacks"
}, {
    $group: {
        _id: "$snacks.name",
        snacks: { $first: "$snacks" },
        count: { $sum: 1 }
    }
}, {
    $sort: {
        count: -1
    }
}], function(err, results) {
    if (err) {
        console.log("something went wrong: " + err);
        return res.status(500).send(err);
    } else {
        return res.status(200).send(results);
    }
});

您将获得以下内容:

{
    "snacks": {
        "nutrients": {
            "protein": 7.5,
            "carbs": 56.5,
            "fat": 10.5
        },
        "servings": 23.8,
        "calories": 526,
        "name": "Dairy milk",
    },
    count: 3
}