[英]Querying a range of dates in Mongoose and Node
我有以下用戶架構:
const User = mongoose.model(
"User",
new mongoose.Schema({
email: String,
password: String,
name: String,
days: [
{
day: Date,
data:
{
average_score: {type: mongoose.Schema.Types.Decimal128, default: 0 }
}
}
]
})
);
在日期字段中,我以 ISO 格式存儲日期,例如 2020-12-29T00:00:00.000Z。 查詢返回所有數據,而不是返回日期范圍之間天數的數據。
User.find({ "_id": getUserId(req), "days.day":{
"$gte": new Date("2021-01-02T00:00:00.000Z"),
"$lt": new Date("2021-01-04T00:00:00.000Z")
}},
function (err, result) {
if (err){
res.status(400).send({data: { message: err }});
return;
}
else if(result)
{
res.status(200).send({data: { message: result }});
}
})
我發現有效的解決方案是:
let itsArray = Array.isArray(req.body.day)
let first = itsArray ? new Date(new Date(req.body.day[0]).toISOString()) : null
let second = itsArray ? new Date(new Date(req.body.day[1]).toISOString()) : null
let theDay = itsArray ? null : new Date(req.body.day)
let now = new Date()
theDay = itsArray ? null : new Date(new Date(theDay).toISOString())
const objectProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond:{ $eq: [ "$$index.day", theDay ] },
}
}
}}
const arrayProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond: {$and: [
{ $gte: [ "$$index.day", first ] },
{ $lte: [ "$$index.day", second ] }
]}
}
}
}}
await User.aggregate([
{$match:{_id: ObjectID(getUserId(req))}},
itsArray ? arrayProject : objectProject
])
.project({'days.day':1, 'days.data':1})
.then(result => {console.log(result})
使用項目、匹配然后過濾似乎可以產生所需的結果。
看來我想要的結果需要一些更高級的 mongodb 功夫:
const objectProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond:{ $eq: [ "$$index.day", theDay ] },
}
}
}}
const arrayProject = { $project: {
days: {
$filter: {
input: "$days",
as: "index",
cond: {$and: [
{ $gte: [ "$$index.day", first ] },
{ $lte: [ "$$index.day", second ] }
]}
}
}
}}
await User.aggregate([
{$match:{_id: ObjectID(getUserId(req))}},
itsArray ? arrayProject : objectProject
])
.project({'days.day':1, 'days.data':1})
.then(result => {console.log(result})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.