Database MongoDB:如何检索过滤后的结果集和相关的集合’;s在被计数之前以不同的方式过滤?
我有一个集合Database MongoDB:如何检索过滤后的结果集和相关的集合’;s在被计数之前以不同的方式过滤?,database,mongodb,Database,Mongodb,我有一个集合C1,看起来像这样(简化): 还有一个集合C2,看起来像这样(再次简化): 我如何在单个查询中检索C1(例如{“special”:“foo”})中的一组过滤记录,其中每个记录都有一个字段c2,其中包含c2中的匹配记录(C1.related等于c2.name): 一个字段lowCount是C2中所有匹配记录的计数,其中{total:{$lte:100} 一个字段midCount是C2中所有匹配记录的计数,其中{total:{$lte:500,$gt:100} 一个字段highCoun
C1
,看起来像这样(简化):
还有一个集合C2
,看起来像这样(再次简化):
我如何在单个查询中检索C1
(例如{“special”:“foo”}
)中的一组过滤记录,其中每个记录都有一个字段c2
,其中包含c2
中的匹配记录(C1.related
等于c2.name
):
- 一个字段
是lowCount
中所有匹配记录的计数,其中C2
{total:{$lte:100}
- 一个字段
是midCount
中所有匹配记录的计数,其中C2
{total:{$lte:500,$gt:100}
- 一个字段
是highCount
中所有匹配记录的计数,其中C2
{total:{$gt:500}
我意识到数据库结构对于需要做的事情来说是笨拙的,但我是在完成之后很久才加入的,现在还不能对它进行彻底的检查。实际代码是使用Spring用Java编写的。您需要使用MongoDb聚合
db.c1.aggregate([
{
$match: {
"special": "foo"
}
},
{
$lookup: {
from: "c2",
localField: "related",
foreignField: "name",
as: "c2"
}
},
{
$addFields: {
lowCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$lte: [
"$$this.total",
100
]
}
}
}
},
midCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$lte: [
"$$this.total",
500
]
}
}
}
},
highCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$gte: [
"$$this.total",
500
]
}
}
}
}
}
}
])
Spring数据允许使用MongoTemplate
类进行聚合(实现MongoOperations)。看看如何将此管道转换为Spring语法
[
// ID and other irrelevant fields omitted
{
"name": "X",
"total": 500
},
{
"name": "Y",
"total": 200
},
{
"name": "Z",
"total": 10
},
// ...more records omitted...
]
db.c1.aggregate([
{
$match: {
"special": "foo"
}
},
{
$lookup: {
from: "c2",
localField: "related",
foreignField: "name",
as: "c2"
}
},
{
$addFields: {
lowCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$lte: [
"$$this.total",
100
]
}
}
}
},
midCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$lte: [
"$$this.total",
500
]
}
}
}
},
highCount: {
$size: {
$filter: {
input: "$c2",
cond: {
$gte: [
"$$this.total",
500
]
}
}
}
}
}
}
])