node.js - MongoDB 请求 : Filter only specific field from embedded documents in embedded array

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我在执行一个 MongoDB 请求时遇到了一些麻烦。我在 Node.js 上下文中使用 MongoDB 3.2Mongoose。这是文档:

{
  _id: ObjectId('12345'),
  name: "The name",
  components: [
    {
      name: "Component 1",
      description: "The description",
      container: {
        parameters: [
          {
            name: "Parameter 1",
            value: "1"
          },
          // other parameters
        ],
        // other information...
      }
    },
    // other components
  ]
}

我想通过以下输出列出特定文档(使用 _id)中特定组件(使用组件名称)的所有参数名称:

['Parameter 1', 'Parameter 2', ...]

我有一个 Mongoose 模式来处理应用程序中的finddistinct方法。我使用 $ 定位运算符尝试了许多操作。这是我的尝试,但返回所有组件的所有参数:

listParameters(req, res) {
  DocumentModel.distinct(
    "components.container.parameters.name", 
    {_id: req.params.modelId, "components.name": req.params.compId},
    (err, doc) => {            
      if (err) {
        return res.status(500).send(err);
      }
      res.status(200).json(doc);
    }
  );
}

但输出是参数名称列表,但没有特定组件的过滤器。您能帮我找到正确的请求吗? (如果可以在 mongoose JS 中使用,但如果是 Mongo 命令行,那就太好了:))

最佳答案

您需要运行一个使用 $arrayElemAt 的聚合管道。 $filter 运算符以获得所需的结果。

$filter 运算符将过滤 components 数组以返回满足给定条件的元素,而 $arrayElemAt 返回数组中给定索引位置处的文档。使用该文档,您可以将嵌套的 parameters 数组元素投影到另一个数组。

结合以上内容,您理想情况下希望进行以下聚合操作:

DocumentModel.aggregate([
    { "$match": { "_id": mongoose.Types.ObjectId(req.params.modelId) } },
    { "$project": {
        "component": {
            "$arrayElemAt": [
                {
                    "$filter": {
                        "input": "$components",
                        "as": "el",
                        "cond": { "$eq": ["$$el.name", req.params.compId] }
                    }
                }, 0
            ]
        }
    } },
    { "$project": {
        "parameters": "$component.container.parameters.name"
    } }
], (err, doc) => {            
  if (err) {
    return res.status(500).send(err);
  }
  const result = doc.length >= 1 ? doc[0].parameters : [];
  res.status(200).json(result);
})

关于node.js - MongoDB 请求 : Filter only specific field from embedded documents in embedded array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050312/

相关文章:

node.js - NPM 在通过 apt 安装时需要 x11

mysql - 序列化的 SQL

arrays - 具有 2 个(或更多)模式类型的 mongoose 数组

mongodb - 使用 Meteor JS 连接 MongoDB 中的两个集合

java - 聚合结果无法正确映射到 Java 对象

node.js - 错误: sort() only takes 1 Argument mongoose

node.js - 编写 Mongoose 插件- plugin() 方法?

javascript - 如何使用 Node.js 在 Heroku 中绑定(bind)端口

node.js - res.render 不加载 Sequelize 数据值

node.js - 如何在模式中动态添加对象?