简体   繁体   English

MongoDB - 查找嵌套文档中的字段计数

[英]MongoDB - find count of field in nested document

I want to find the count of all occurrences of the field "36" from the the following json: The count should be 2. The field is present in any of the data.TL.TXXX documents.我想从以下 json 中查找所有出现的字段“36”的计数:计数应为 2。该字段存在于任何 data.TL.TXXX 文档中。 I tried the find() method of mongoDB, but could only search in one document at a time.我尝试了 mongoDB 的 find() 方法,但一次只能搜索一个文档。 Probably I need a regex here.可能我在这里需要一个正则表达式。 Can someone help me out:有人可以帮我吗:

{
    "_id" : ObjectId("1115dd31af82eb3ca8028188"),
    "data" : {
        "TL" : {
            "T001" : {
                "11" : "05012017",
                "13" : "0",
                "28" : "000",
                "29" : "00000",
                "30" : "01012017",
                "31" : "01122014",
                "36" : "10000",
                "37" : "3000",
                "38" : "29.81",
                "39" : "1",
                "44" : "03",
                "02" : "NOT DISCLOSED",
                "04" : "10",
                "05" : "1",
                "08" : "16122014"
            }
        }
    }
},
{
    "_id" : ObjectId("345222ddaf82eb1b262be44f"),
    "data" : {
        "TL" : {
            "T004" : {
                "10" : "19052013",
                "11" : "15062013",
                "12" : "37903",
                "13" : "0",
                "28" : "00000000",
                "29" : "000000000000000000",
                "30" : "01052013",
                "31" : "01062011",
                "44" : "03",
                "02" : "NOT DISCLOSED",
                "04" : "10",
                "05" : "1",
                "08" : "27062011",
                "09" : "08052013"
            },
            "T005" : {
                "11" : "10012017",
                "12" : "114525",
                "13" : "8853",
                "28" : "00000300000300000",
                "29" : "000000XXX0000000010",
                "30" : "01012017",
                "31" : "01022014",
                "36" : "100000",
                "37" : "10000",
                "44" : "03",
                "45" : "6714",
                "02" : "NOT DISCLOSED",
                "04" : "10",
                "05" : "1",
                "08" : "27062011",
                "09" : "12122016"
            },
        }
    }
}

You can use below aggregation您可以使用以下聚合

db.collection.aggregate([
  { $project: { "data.TL": { $objectToArray: "$data.TL" }}},
  { $unwind: "$data.TL" },
  { $project: { data: { $objectToArray: "$data.TL.v" }}},
  { $unwind: "$data" },
  { $group: { _id: "$data.k", count: { $sum: 1 }}}
]);

MongoPlayground Mongo游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM