Mongodb 比较对象数组中数组的大小
我想Mongodb 比较对象数组中数组的大小,mongodb,mongoose,mongodb-query,aggregation-framework,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我想查找所有scocompetitions.length大于competitions.length的文档 以下是一些示例文档: { "_id" : ObjectId("59b28f432b4353d3f311dd1b"), "name" : "Ford Focus RS 2008", "requirements" : [ { "rankType" : "D1", "competitions" : [
查找所有scocompetitions.length
大于competitions.length的文档
以下是一些示例文档:
{
"_id" : ObjectId("59b28f432b4353d3f311dd1b"),
"name" : "Ford Focus RS 2008",
"requirements" : [
{
"rankType" : "D1",
"competitions" : [
ObjectId("59b151fd2b4353d3f3116827"),
ObjectId("59b151fd2b4353d3f3116829")
],
"sCompetitions" : [
"Rallye Monte-Carlo",
"Rally Sweden"
]
},
{
"rankType" : "A3",
"competitions" : [
ObjectId("59b151fd2b4353d3f3116f6b")
],
"sCompetitions" : [
"Rally Italia Sardegna",
"Neste Rally Finland"
]
}
]
},
{
"_id" : ObjectId("0000b28f432b4353f311dd1b"),
"name" : "Ford Focus RS 2012",
"requirements" : [
{
"rankType" : "D1",
"competitions" : [
ObjectId("59b151fd2b4353d3f3116827"),
ObjectId("59b151fd2b4353d3f3116829")
],
"sCompetitions" : [
"Rallye Monte-Carlo",
"Rally Sweden"
]
},
{
"rankType" : "A3",
"competitions" : [
ObjectId("59b151fd2b4353d3f3116f6b"),
ObjectId("59b151fd2b4353d3f3116f6b")
],
"sCompetitions" : [
"Rally Italia Sardegna",
"Neste Rally Finland"
]
}
]
}
因此,查看示例,它只会返回ObjectId(“59b28f432b4353d3f311dd1b”)
我的问题是,requirements
本身就是一个数组,所以我需要以某种方式对它进行迭代无需“迭代”。您真正需要的是在从返回结果后进行检查。你可以在一个动作中完成这一切:
因此,对每个数组元素进行简单的比较,然后如果这些元素中的“任意”为true
,则文档将从结果中“保留”或“删除”。谢谢。出于好奇,我可以在
中的中使用`或`运算符吗?如果我想找到scocompetitions.length
大于competitions.length
或rankType=='CC'
@Cornwell的所有文档,你可以随意使用。这里唯一一个为每个数组元素返回布尔值的点。这是因为这是您要求的条件。但是,也返回布尔值的任何一个或各种其他函数都可以用于相同的目的。
Model.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$anyElementTrue": {
"$map": {
"input": "$requirements",
"as": "r",
"in": {
"$gt": [
{ "$size": "$$r.sCompetitions" },
{ "$size": "$$r.competitions" }
]
}
}
}
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])