MongoDB 查询从现在到两小时前创建的文档

标签 mongodb mongoose

我的节点中有一个 mongodb 查询,它根据几个条件查找文档:

Follow.find({
    user: req.user._id
    , followed: req.params.userId
}).populate(populateQuery).exec(function (err, results) {
    next.ifError(err);
    //res.send(results);
    if(results.length > 0){
        console.log('****** found!!!');
        console.log(results);
    }
});

所以这很好用。但是,我需要找到仅在现在和两个小时前之间创建的记录。 如何正确格式化查询对象中的日期对象?

{
    user: req.user._id
    , followed: req.params.userId
    ,dateCreated: {
        $gte: ISODate(<TWO HOURS AGO>),
        $lt: ISODate(<NOW>)
    }
}

最佳答案

创建两个日期对象,分别表示现在和 2 小时前的日期时间,如下所示:

// Define
var TWO_HOURS = 2*60*60*1000, // milliseconds
    now = new Date(),
    twoHoursAgoDate = new Date(now.getTime() - TWO_HOURS);

Follow.find({
        user: req.user._id,
        followed: req.params.userId,
        dateCreated: { $gte: twoHoursAgoDate, $lt: now }
    }).populate(populateQuery).exec(function (err, results) {
        next.ifError(err);
        //res.send(results);
        if(results.length > 0){
            console.log('****** found!!!');
            console.log(results);
        }
    });

更好的方法是使用 momentjs 库,它简化了日期时间操作,特别是你会使用 subtract() 方法:

// Define
var now = moment(),
    twoHoursAgoDate = moment().subtract(2, 'hours');

关于MongoDB 查询从现在到两小时前创建的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316842/

相关文章:

python - jupyter笔记本-导入错误: No module named 'bson'

java - 由 : java. lang.VerifyError 引起:无法链接 com/fasterxml/jackson/databind/type/ReferenceType:无法从最终类继承

database - Go MongoDB (mgo) - 不释放关闭的连接

javascript - Mongoose 填充虚拟而不是整个架构

javascript - JS - Express - Mongoose 在发送响应之前执行所有 Mongoose 的 promise

javascript - Mongoose.js 和使用 Regexp 的查询对象

javascript - MongoDB:更新集合中的数组项不起作用

java - Apache Kafka Mongodb 连接器的 ClassNotFoundException : com. mongodb.ConnectionString

javascript - 如何使用 JavaScript 在 mongodb 中设置唯一 id

node.js - 在 Mongoose 中将数组更新到文档中