从嵌入式文档返回数组

时间:2017-06-09 07:30:29

标签: node.js mongodb mongodb-query embedded-database embedded-documents

我有mongodb集合名称属性中的数据。

{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }

我只想要

 [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]

结果我试过这个

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});

这个给予

{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}

如何获得上面给出的结果。

3 个答案:

答案 0 :(得分:0)

假设您使用的是mongoose that returns promises之类的内容,您可以使用查询结果

return req.db.collection('FeatureSettings')
.findOne({feature_type: req.params.feature_type}, {features: 1})
.then((result) => {
    return result.features;
});

答案 1 :(得分:0)

您必须像这里一样从投影中排除_id:

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1, _id:0});

答案 2 :(得分:0)

您可以尝试此操作仅返回features数组值。

req.db.collection('FeatureSettings')
 .findOne({feature_type: req.params.feature_type}, {features:1, _id:0}).features;

// if you use mongoose can use 
return req.db.collection('FeatureSettings')
  .findOne({feature_type: req.params.feature_type}, {features:1, _id:0})
  .exec()
  .then((result) => {
     return result.features;
  });