![](/img/trans.png)
[英]How to compare the two dates and result it into the textbox by javascript
[英]How to subtract two dates and compare the result against another field?
我是MongoDB的新手。 我有一个具有以下文档结构的集合:
{
"active": true,
"days": [],
"start_date": ISODate("..."),
"end_date": ISODate("..."),
"frequency": 600000,
"latest_execution_date": ISODate("...")
}
{
"active": false,
"days": [1, 2, 3],
"start_date": ISODate("..."),
"end_date": ISODate("..."),
"frequency": 600000,
"latest_execution_date": ISODate("...")
}
{
"active": true,
"days": [2, 5],
"start_date": ISODate("..."),
"end_date": ISODate("..."),
"frequency": 600000,
"latest_execution_date": ISODate("...")
}
我想找到,带有“days”数组或一周当前日期的活动文档位于数组中,当前日期介于“start_date”和“end_date”之间,“latest_execution_date”与当前日期之间的差异大于“频率”。
我已创建此查询,它对我有用,但我使用的MongoDB服务器不再支持“$ where”。
db.myCollection.find({
$where: function() {
const currentDate = new Date();
const latestExecution = new Date(this.latest_execution_date);
return (
this.active &&
this.start_date <= currentDate &&
this.end_date >= currentDate &&
(this.days.includes(currentDate.getDay()) || this.days.length === 0) &&
(this.latest_execution_date === null || ((currentDate.valueOf() - latestExecution.valueOf()) >= this.frequency))
);
}
})
我试图通过“聚合”替换“查找”,但我坚持减法和比较,这就是我现在所拥有的但是$ cmp无法正常工作。
db.myCollection.aggregate([{
$project: {
active: "$active",
start_date: "$start_date",
end_date: "$end_date",
days: "$days",
frequency: "$frequency"
latest_execution_date: "$latest_execution_date",
dateDifference: {
$subtract: [ new Date(), "$latest_execution_date" ]
},
compare: {
$cmp: [ "$dateDifference", "$frequency" ]
}
}
},
{
$match: {
active:{$eq:true},
start_date:{$lte: ISODate("...")},
end_date:{$gte: ISODate("...")},
$and: [
{ $or:[ { days:{$size:0}}, { days:{$elemMatch:{$eq:<day of the week>} } }] },
{ $or: [ { latest_execution_date: { $eq: null } }, { compare: { $lte: 0 } } ] }
]
}
}
])
我采用这种方法的主要问题是“$ cmp”总是返回“-1”,如果“频率”更大或没有,则无关紧要。 我检查了数据类型,频率是Int32,dateDifference是Int64。 将频率转换为Int64(频率:{$ convert:{input:“$ frequency”,to:“long”}})我得到了同样的结果。
有人知道如何解决这个问题吗? 或者有一个不同的approch来解决这个问题? 我们非常欢迎所有的建议,建议或评论。
谢谢!
我没时间发布我的解决方案。 我把它放在这里以防它可以帮到某人。
db.myCollection.aggregate([{
$project: {
...
dateDifference: {
$subtract: [{ $subtract: [new Date(), '$latest_execution_date'] }, '$frequency']
}
}
},
{
$match: {
...
$and: [
{ $or:[ { days:{$size:0}}, { days:{$elemMatch:{$eq:<day of the week>} } }] },
{ $or: [ { latest_execution_date: { $eq: null } }, { dateDifference:{$gte:0}} ] }
]
}
}
])
基本上,我意识到我无缘无故地使解决方案变得复杂,只需添加嵌套的Subtraction就足够了,然后检查结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.