检索其"日期"在最后6分钟内的所有日期



我在MongoDB中存储了一个Product集合。它具有属性date:

const productSchema = new mongoose.Schema<ProductAttrs>({
date: {
type: Date, 
required: true,
}
...
})

我想检索与当前时间相比,date在最后6分钟内的所有产品。在猫鼬身上找回它的有效方法是什么?

我在我的项目中使用express.js+typescript+mongoose v5.11。

您必须使用Mongoose来搜索时间大于now - 6 minutes的每条记录
我没有办法测试它,但查询应该是这样的:

const sixMinutes = (6*60*1000); // 6 minutes
let sixMinutesAgo = new Date();
sixMinutesAgo.setTime(sixMinutesAgo.getTime() - sixMinutes);
const products = Product.find({ 
date: {
$gte: sixMinutesAgo
}
})

如果MongoDB服务器版本是5.0,则可以使用新的运算符$dateDiff。在这种情况下,它非常方便,您甚至不需要aggregate:

db.collection.find({
"$expr": {
"$lte": [
{
"$dateDiff": {
startDate: "$date",
endDate: new Date(),
unit: "minute"
}
},
6
]
}
})

它允许您指定unit字段,在我看来,这使得查询非常简单。

$expr计算表达式并返回truefalse,仅此而已。如果表达式结果为true,则返回该行,否则不返回。

$lte表示小于或等于(<=运算符(,并且只有当第一个参数大于或等于第二个运算符时才返回true。基本上,这就是它在伪代码中所做的:

foreach doc in collection
if (minute)(currentDate - document.date) <= 6 then
return document

最新更新