MongoDB-格式响应

MongoDB-格式响应,mongodb,Mongodb,我有一个集合,看起来像: [ { "_id": 1, "title": "dummy title", "settings": [ { "type": "light", "status": "enabled"

我有一个集合,看起来像:

[
  {
    "_id": 1,
    "title": "dummy title",
    "settings": [
            {
                "type": "light",
                "status": "enabled"
            },
            {
                "type": "flare",
                "status": "disabled"
            },
            {
                "type": "toolbar",
                "status": "endbale"
            }
        ]
  }
]
我想创建一个查询来获取文档,但只使用数组中活动设置的类型,例如,在上述情况下,结果应该是:

[
    {
      "_id": 1,
      "title": "dummy title",
      "enabled_settings": ["light", "toolbar"]
    }
  ]

如何实现这样的效果?

您可以在投影部分使用
$reduce
$cond
条件将检查状态是否已启用,然后concat和最后返回值

db.collection.find({},
{
  _id: 1,
  title: 1,
  settings: {
    $reduce: {
      input: "$settings",
      initialValue: [],
      in: {
        $concatArrays: [
          "$$value",
          {
            $cond: [
              { $eq: ["$$this.status", "enabled"] },
              ["$$this.type"],
              []
            ]
          }
        ]
      }
    }
  }
})