node.js - 值嵌套在数组中时如何区分(计数)值?
问题描述
我有一个像这样的数据样本:
"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
}
]
有人可以帮我查询吗?
解决方案
您需要在$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" }
}}
])
推荐阅读
- c++ - C ++ JSON添加数组作为键
- php - php:HTML项目符号列表到多维数组
- java - 扁平化多级双向链表 leetcode
- php - 如何在php中设置标题以确保安全
- spring-boot - 如何将闪存消息从控制器调用到百里香模板
- ruby-on-rails - 在哪里可以找到支持 ruby 1.8 的 simplecov 的 gem 包
- flutter - 购物车小部件在颤动中热重新加载时消失
- c++ - Visual Studio 2019 是否可以将文件输出为大写?
- angular - ArcGIS - 错误:编辑时不允许此操作 [可编辑]
- android - 抗锯齿导致recyclerview滞后