【发布时间】:2019-07-19 23:20:43
【问题描述】:
我在 Mongo 中有一个架构如下:
{
"_id" : ObjectId("5c73cbeb2258414c5d9bf2a5"),
"make" : {
"name" : "Excel Boats",
"models" : [
{
"year" : 2012,
"name" : "1860V86",
"subModels" : [
{
"name" : "",
"controlNumber" : "OB1133079",
"protoTypeNumber" : "",
"status" : "A",
"classCode" : "OB",
"boatType" : "UT",
"powerType" : "OU",
"boatLength" : 18,
"horsePower" : 70,
"hullConstruction" : "A",
"msrp" : 9589,
"lowCostAmount" : 4700,
"highCostAmount" : 5270,
"retailAmount" : 6540,
"notes" : ""
},
{
"name" : "",
"controlNumber" : "OB1133080",
"protoTypeNumber" : "",
"status" : "A",
"classCode" : "OB",
"boatType" : "UT",
"powerType" : "OU",
"boatLength" : 18,
"horsePower" : 90,
"hullConstruction" : "A",
"msrp" : 10889,
"lowCostAmount" : 4900,
"highCostAmount" : 5970,
"retailAmount" : 6840,
"notes" : ""
}
]
}
]
}
我正在尝试过滤数据,以便我可以带回 mrsp 值仅为 9589 的子模型。这是我目前拥有的代码,但它为子模型带回了一个空数组。
db.boats.aggregate({
$match: {
$and: [
{'make.name': 'Excel Boats'},
{'make.models.year': 2012},
{'make.models.name': '1860V86'}
]
}
},
{
$project: {
'make.models.subModels': {
$filter: {
input: '$make.models.subModels',
as: 'subModel',
cond: {$eq: ['$$subModel.msrp', 10889]}
}
}
}
}
).pretty()
这是我运行查询时的结果
{
"_id" : ObjectId("5c73cbeb2258414c5d9bf2a5"),
"make" : {
"models" : [
{
"subModels" : [ ]
}
]
}
}
我希望得到的是这个结果
{
"_id" : ObjectId("5c73cbeb2258414c5d9bf2a5"),
"make" : {
"models" : [
{
"subModels" : [ {
"name" : "",
"controlNumber" : "OB1133079",
"protoTypeNumber" : "",
"status" : "A",
"classCode" : "OB",
"boatType" : "UT",
"powerType" : "OU",
"boatLength" : 18,
"horsePower" : 70,
"hullConstruction" : "A",
"msrp" : 9589,
"lowCostAmount" : 4700,
"highCostAmount" : 5270,
"retailAmount" : 6540,
"notes" : ""
} ]
}
]
}
}
如果有人能提供我出错的任何信息,我将不胜感激。我感觉它与数组中的嵌套数组有关,因为我能够毫无问题地获取模型数组中的信息。
提前致谢!
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework