select 计算 MongoDB 中的子查询
select count subquery in MongoDB
这是我在 MongoDB 中的查询:
{ runCommand :
{ aggregate : 'record',
pipeline : [
{ $match : { "_id" : {
"$binary" : "HUjjlL5SCpVKNVnedOk+nQ==", "$type" : "3"
}}},
{ $project : { Results : 1 }},
{ $unwind : '$Results'}
],
cursor: {}
}
}
我想向 "Result.Type" = "SpecificResult"
.
的 COUNT 个结果添加子查询
这是文档示例:
{
"_id": Binary("HUjjlL5SCpVKNVnedOk+nQ==", 3),
"Header": {
"FileFormatVersion": "2.0",
"Filename": "1231434534654",
"ReferenceNumber": "235423645677"
},
"Results": [
{
"Type": "Title",
"Seq": "1111",
"Title": "Some Title",
"SubTitle": "",
"TitleLevel": "1"
},
{
"Type": "Title",
"Seq": "056330010",
"Title": "Some Subtitle",
"SubTitle": "",
"TitleLevel": "2"
},
{
"Type": "Result",
"Seq": "0560002200040",
"ResultValue": "value"
},
{
"Type": "SpecificResult",
"Seq": "0123234010",
"Title": "",
"Name": "Name",
"ResultComments": "Comment1"
},
{
"Type": "SpecificResult",
"Seq": "0123234010",
"Title": "",
"Name": "Name222",
"ResultComments": "Comment1"
}
]
}
在 SQL 中看起来像:
SELECT *, (select count (*) from Results where Type = 'SpecificResult') FROM Results;
如何在 MongoDB 中执行此操作?
$filter
迭代 Results.Type
数组的循环,检查条件是否类型与 SpecificResult
匹配,$size
获取 $filter
返回结果的计数,
{
runCommand : {
aggregate : 'record',
pipeline : [
{ $match : { "_id" : { "$binary" : "HUjjlL5SCpVKNVnedOk+nQ==", "$type" : "3" } } },
{
$project : {
Results : 1,
ResultCount: {
$size: {
$filter: {
input: "$Results.Type",
cond: { $eq:["$$this", "SpecificResult"] }
}
}
}
}
},
{ $unwind : '$Results' }
],
cursor: {}
}
}
这是我在 MongoDB 中的查询:
{ runCommand :
{ aggregate : 'record',
pipeline : [
{ $match : { "_id" : {
"$binary" : "HUjjlL5SCpVKNVnedOk+nQ==", "$type" : "3"
}}},
{ $project : { Results : 1 }},
{ $unwind : '$Results'}
],
cursor: {}
}
}
我想向 "Result.Type" = "SpecificResult"
.
这是文档示例:
{
"_id": Binary("HUjjlL5SCpVKNVnedOk+nQ==", 3),
"Header": {
"FileFormatVersion": "2.0",
"Filename": "1231434534654",
"ReferenceNumber": "235423645677"
},
"Results": [
{
"Type": "Title",
"Seq": "1111",
"Title": "Some Title",
"SubTitle": "",
"TitleLevel": "1"
},
{
"Type": "Title",
"Seq": "056330010",
"Title": "Some Subtitle",
"SubTitle": "",
"TitleLevel": "2"
},
{
"Type": "Result",
"Seq": "0560002200040",
"ResultValue": "value"
},
{
"Type": "SpecificResult",
"Seq": "0123234010",
"Title": "",
"Name": "Name",
"ResultComments": "Comment1"
},
{
"Type": "SpecificResult",
"Seq": "0123234010",
"Title": "",
"Name": "Name222",
"ResultComments": "Comment1"
}
]
}
在 SQL 中看起来像:
SELECT *, (select count (*) from Results where Type = 'SpecificResult') FROM Results;
如何在 MongoDB 中执行此操作?
$filter
迭代Results.Type
数组的循环,检查条件是否类型与SpecificResult
匹配,$size
获取$filter
返回结果的计数,
{
runCommand : {
aggregate : 'record',
pipeline : [
{ $match : { "_id" : { "$binary" : "HUjjlL5SCpVKNVnedOk+nQ==", "$type" : "3" } } },
{
$project : {
Results : 1,
ResultCount: {
$size: {
$filter: {
input: "$Results.Type",
cond: { $eq:["$$this", "SpecificResult"] }
}
}
}
}
},
{ $unwind : '$Results' }
],
cursor: {}
}
}