简体   繁体   English

查询mongodb以获取最近30分钟内创建的文档

[英]Query mongodb to get documents created within last 30 minutes

I'm in Central European Summer Time (CEST) at 15:08 I added document to my collection. 我在中部欧洲夏令时间(CEST)15:08,将文档添加到集合中。 In model to new Schema I'm passing timestamps: true . new Schema模型中,我传递了timestamps: true Its createdAt is incorrect, it's two hours too early: 它的createdAt不正确,还早两个小时:

createdAt:2019-08-21 13:08:39.219

Why? 为什么? Also what does .219 at the end mean? 另外, .219到底是什么意思? Lastly how can I query this collection to get every one which createdAt is within last 30 minutes? 最后,我如何查询此集合以获取过去30分钟内的createdAt中的每一个?

const c = await Collection.find({
    createdAt: {
        $gte: new Date() // ???
    }
});

I've combined answers with comments and tried something like this: 我将答案与评论结合在一起,并尝试了以下操作:

const d = new Date(
    new Date().getTime() + new Date().getTimezoneOffset() * 60000 - 30 * 60000
);
const c = await Collection.find({
    createdAt: { $gte: d }
});

but it doesn't seem to work correctly. 但它似乎无法正常工作。 I execute this code at 15:47 CEST which is 13:47 UTC so earliest document should be from 13:17 but I get results with "createdAt": "2019-08-21T12:43:38.395Z", . 我在美国东部标准时间13:47 CEST的15:47 CEST执行此代码,因此最早的文档应来自13:17,但得到的结果为"createdAt": "2019-08-21T12:43:38.395Z",

You can create a date that ignores your browser timezone: 您可以创建一个忽略浏览器时区的日期:

function newDateTZSafe(){
    var now = new Date();
    return new Date(now.getTime() + now.getTimezoneOffset() * 60000);
}

or as alternative, if you heavily rely on dates, use moment.js 或者,如果您严重依赖日期,请使用moment.js

**Try this query**
const c = await Collection.find({
    createdAt: {
        "$gte" : new Date(ISODate().getTime() - 1000 * 60 * 30) }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM