首页 > 解决方案 > 值嵌套在数组中时如何区分(计数)值?

问题描述

我有一个像这样的数据样本:

"diagnostics" : {

    "_ID" : "554bbf7b761e06f02fef3561",

    "tests" : [ 
        {
            "_id" : "59d678064e4645ec562a37e2",
            "name" : "RBC",
        }, 
        {
            "_id" : "59d678064e4645ec562a37e1",
            "name" : "Calcium",
        }
    ]
}

我想获得所有不同的 _ID 和所有测试组的计数,其中的名称如下所示:

"_ID" : "554bbf7b761e06f02fef3561"{ {"name" : "Calcium", count :(count of Calcium)},{"name" : "RBC", count :(count of RBC)}

要记住的是测试在诊断内部并包含任意数量的 $name 字段,它可以是两次或一次或任意次数,我想要每个不同名称的单独计数。

db.collection('transactions').aggregate([
{ $unwind : '$diagnostics.tests' }, 
  {  $group : {
  _id: {
    "Test_Name" : '$diagnostics.tests.name',
    "ID" : '$diagnostics._id'
  },
  test_count: {  $sum: 1  } 
}
 }  
])

我得到这样的结果

[
  {
    "_id": {
      "Test_Name": "Fasting Blood Sugar",
      "ID": "554bbf7b761e06f02fef3561"
    },
    "test_count": 76
  },
  {
    "_id": {
      "Test_Name": "Fasting Blood Sugar",
      "ID": "566726c35dc18d13242fffcc"
    },
    "test_count": 1
  },
  {
    "_id": {
      "Test_Name": "CBC - 7 Part",
      "ID": "566726c35dc18d13242fffcc"
    },
    "test_count": 1
  },
  {
    "_id": {
      "Test_Name": "RBC",
      "ID": "554bbf7b761e06f02fef3561"
    },
    "test_count": 1
  },
  {
    "_id": {
      "Test_Name": "Fasting Blood Sugar",
      "ID": "5a2c9edfe0d0ec71aef1e526"
    },
    "test_count": 6
  },
  {
    "_id": {
      "Test_Name": "Calcium",
      "ID": "554bbf7b761e06f02fef3561"
    },
    "test_count": 77
  }
]

有人可以帮我查询吗?

标签: node.jsmongodbgroup-byaggregatedistinct

解决方案


您需要在$group这里使用多个阶段。

首先通过“名称”$unwind进行测试,$group然后将其调整为原始大小,最后$group通过“diagnostics_ID”调整测试数量,您可以检查“测试”数组的$size

db.collection.aggregate([
  { "$unwind": "$diagnostics.tests" },
  { "$group": {
    "_id": {
      "_id": "$diagnostics.tests.name",
      "diagnosticID": "$diagnostics._ID"
    },
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": {
      "_ID": "$_id.diagnosticID"
    },
    "tests": {
      "$push": {
        "name": "$_id._id",
        "count": "$count"
      }
    }
  }},
  { "$project": {
    "diagnostics._ID": "$_id._ID",
    "diagnostics.tests": "$tests",
    "_id": 0,
    "testCount": { "$size": "$tests" }
  }}
])

代码片段


推荐阅读