在Mongo DB中查询带有条件的子元素的数量

时间:2020-01-13 15:25:03

标签: mongodb aggregation-framework

我是Mongo DB的新手,希望在以下查询任务中获得一些帮助。

我有一组如下所示的文档:

{
    "field_1" : {
      "subfield_1" : {
        "subsubfield_1" : "true",
        "subsubfield_2" : "false",
        "subsubfield_3" : "true"
        },
      "subfield_2" : "sf2"
      },
    "field_2" : {
      "subfield_1" : {
        "subsubfield_1" : "true",
        "subsubfield_2" : "false"
        },
      "subfield_2" : "sf2"
      },
    "field_3" : {
      "subfield_1" : {
        "subsubfield_1" : "true",
        "subsubfield_2" : "false",
        "subsubfield_3" : "false"
        },
      "subfield_2" : "sf2"
      }
}

我正在尝试查询,以便我为集合中的每个元素(1)确切指定要返回的字段(在这种情况下为subfield_1subfield_2,而(2)为subfield_1仅返回true个元素的计数。因此,我希望输出如下所示:

{
  {
    "subfield_1" : 2,
    "subfield_2" : "sf2"
  },
  {
    "subfield_1" : 1,
    "subfield_2" : "sf2"
  },
  {
    "subfield_1" : 1,
    "subfield_2" : "sf2"
  }
}

我一直在尝试这段代码,但这只给了我subfield_1中每个元素的条目数:

db.getCollection('myCollection').aggregate(
  {
  $match: {<some other condition>}
  },
  {
  $project: {
    subfield_2: 1, 
    subfield_1: {'$size': '$subfield_1'}
  }
  }
)

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要运行$objectToArray将嵌套的构造函数转换为键和值的数组,然后使用$unwind为每个子文档获取一个单独的文档。然后,您可以与$filter一起运行另一个$objectToArray,以仅获取true值:

db.collection.aggregate([
    {
        $project: {
            doc: { $objectToArray: "$$ROOT" }
        }
    },
    {
        $unwind: "$doc"
    },
    {
        $match: { $expr: { $ne: [ "$doc.k", "_id" ] } }
    },
    {
        $project: {
            _id: 0,
            subfield_1: { $size: { $filter: { input: { $objectToArray: "$doc.v.subfield_1" }, cond: { $eq: [ "$$this.v", "true" ] } } } },
            subfield_2: "$doc.v.subfield_2"
        }
    }
])

Mongo Playground