Query the count of sub elements with condition in Mongo DB

会有一股神秘感。 提交于 2020-01-24 19:51:05

问题


I am new to Mongo DB and would appreciate some help with the following query task.

I have a collection of documents that looks like below:

{
    "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"
      }
}

And I am trying to query such that I, for each element in the collection (1) specify exactly which fields to return (in this case subfield_1 and subfield_2, and, (2) for subfield_1only return the count of trueelements. So I would like the output to look like:

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

I have been trying this code but that only gives me the number of entries in subfield_1for each element:

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

Thanks in advance!


回答1:


You need to run $objectToArray to transform your nested structer into an array of keys and values and then use $unwind to get a separate document for every sub-document. Then you can run another $objectToArray along with $filter to get only true values:

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



来源:https://stackoverflow.com/questions/59719488/query-the-count-of-sub-elements-with-condition-in-mongo-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!