[{
"_id" : ObjectId("5f3d0f13fd6fd6667f8f56d6"),
"name" : "A",
"prices" : [
{
"_id" : ObjectId("5f3d0f16fd6fd6667f8f57fb"),
"d" : ISODate("2019-08-19T00:00:00.000Z"),
"h" : 182.1,
},
{
"_id" : ObjectId("5f3d0f16fd6fd6667f8f57fc"),
"d" : ISODate("2019-08-20T00:00:00.000Z"),
"h" : 182.1,
},
{
"_id" : ObjectId("5f3d0f16fd6fd6667f81f57fc"),
"d" : ISODate("2019-08-21T00:00:00.000Z"),
"h" : 182.1,
}
]
}]
输入:
from: '2019-08-20'
to: '2019-08-21'
预期输出
[{
"_id" : ObjectId("5f3d0f13fd6fd6667f8f56d6"),
"name" : "A",
"prices" : [
{
"_id" : ObjectId("5f3d0f16fd6fd6667f8f57fc"),
"d" : ISODate("2019-08-20T00:00:00.000Z"),
"h" : 182.1,
},
{
"_id" : ObjectId("5f3d0f16fd6fd6667f81f57fc"),
"d" : ISODate("2019-08-21T00:00:00.000Z"),
"h" : 182.1,
}
]
}]
所以我想过滤prices array
,以便它仅基于变量d
返回给定日期范围内的项目
是某种形式的聚合。
mongoose.model("stock").aggregate(...)
$unwind
$filter
,$gte
,$gle
的某些组合
答案 0 :(得分:2)
您可以执行以下操作
db.collection.aggregate([
{
$project: {
items: {
$filter: {
input: "$prices",
as: "price",
cond: {
"$and": [//only date conditions
{
$gte: [
"$$price.d",
new Date("2019-08-20")
]
},
{
$lte: [
"$$price.d",
new Date("2019-08-21")
]
}
]
}
}
}
}
}
])