我有一个如下车型
{
"_id": "54b8a71843286774060b8bed",
"name": "Car1",
"active": true,
"model": [
{
"name": "Model1",
"active": true,
"_id": "54b8a71843286774060b8bee",
"available": [
{
"Day": "Mon",
"quantity": "6"
},
{
"Day": "Tue",
"quantity": "6"
},
{
"Day": "Wed",
"quantity": "6"
},
{
"Day": "Thurs",
"quantity": "6"
},
{
"Day": "Fri",
"quantity": "0"
}
]
},
{
"name": "Model2",
"active": true,
"_id": "54b8a71843286774060b8bef",
"available": [
{
"Day": "Mon",
"quantity": "6"
},
{
"Day": "Tue",
"quantity": "6"
},
{
"Day": "Wed",
"quantity": "6"
},
{
"Day": "Thurs",
"quantity": "6"
},
{
"Day": "Fri",
"quantity": "6"
}
]
},
{
"name": "Model3",
"active": true,
"_id": "54b8a71843286774060b8beg",
"available": [
{
"Day": "Mon",
"quantity": "6"
},
{
"Day": "Tue",
"quantity": "6"
},
{
"Day": "Wed",
"quantity": "6"
},
{
"Day": "Thurs",
"quantity": "6"
},
{
"Day": "Fri",
"quantity": "0"
}
]
}
]
}
我正在尝试在特定日期搜索汽车的可用性。 就像我选择星期五然后它应该返回我星期五数量超过0的汽车,但目前它将返回所有数量为0的汽车。
我写了如下查询
Car.find({ '活跃':是的, 'model.available':{ $ elemMatch:{ 数量:{$ gte:1} } } })
但它还返回了数量为0的文件。
答案 0 :(得分:2)
为此,您需要aggregation pipeline。
以下代码段执行此操作:
{name: "Car1": 1, models: [{name: "Model1"}, {name: "Model2"}, {name: "Model3"}]}
{name: "Car1", models: {name: "Model1"}}
& {name: "Car1", models: {name: "Model2"}}
& {name: "Car1", models: {name: "Model3"}}
。db.cars.aggregate([
// First, we do your query, which will return
// every document that has _at least one_
// model that is available.
{$match: {
'active': true,
'model.available': {$elemMatch: {
'quantity': {$gte: 1},
'Day': 'Fri'
}}
}},
// We split up the found documents,
// every document will now have exactly
// one 'model' in it.
{$unwind: "$model"},
// We now filter the split documents.
{$match: {
'model.available': {$elemMatch: {
'quantity': {$gte: 1},
'Day': 'Fri'
}}
}},
// If you want, you can now glue the
// models back together again.
{$group: {
_id: "$_id", // Group all documents with the same _id
name: {$first: "$name"},
active: {$first: "$active"},
model: {$push: "$model"} // Make an array of models
}}
])
重要说明:要使$gte
生效,您需要将数量存储为数字,而不是字符串。由于您的示例将数字存储为字符串,因此您可能需要在数据库中仔细检查它们。