查找包含特定值的数组元素

时间:2019-01-29 08:27:25

标签: arrays mongodb

我有这样的模式:

{
    "_id" : ObjectId("55de668b4ac1fc9e75552db0"),
    "name" : "john",
    "documents" : {
        "number" : "125",
        "_clas" : "some class type here"
    }
}

我如何找到所有以“付款”作为其文件类别类型的人? 我需要类似的输出

john, 125
john, 456
Ann, 234
Ivan, 345

但是输出中不应带有_class =“ qwe”的元素

1 个答案:

答案 0 :(得分:0)

如果您只想过滤_class为“ pay”的文档,则可以执行简单的查找查询

db.collection.find({
  "documents._clas": "pay"
})

如果您还希望按照给定的方式来构造响应,则必须使用汇总。

db.collection.aggregate([
  {
    "$match": {
      "documents._clas": "pay"
    }
  },
  {
    "$project": {
      "name": 1,
      "product": "$documents._clas"
    }
  }
])

$ match阶段查找与您所需查询匹配的文档(_class为“ pay”),$ project阶段以所需格式获取输出。

编辑: 考虑到文档是数组,解决方案将是

db.collection.aggregate([
  {
    "$match": {
      "documents._clas": "pay"
    }
  },
  {
    "$project": {
      "name": 1,
      "product": {
        $filter: {
          input: "$documents",
          as: "document",
          cond: {
            $eq: [
              "$$document._clas",
              "pay"
            ]
          }
        }
      }
    }
  }
])

match阶段会获取具有薪水作为数组元素中任何一个元素的文档,如果您认为集合中的所有文档将至少有一个薪水_clas,则可以跳过该阶段。

相关问题