【问题标题】:How to filter MongoDB records by date and time?如何按日期和时间过滤 MongoDB 记录?
【发布时间】:2015-05-20 17:58:40
【问题描述】:

我正在学习如何使用 MeteorJS,我的记录如下:

meteor:PRIMARY> db.meals.find()
{ "_id" : "kHjRCXRRoC6JLYjJY", "name" : "Spaghetti & Meatballs", "calories" : "300", "eatenAt" : ISODate("2015-05-20T07:07:00Z"), "userId" : "movpJRhRMwyMZDBqf", "author" : "sergiotapia" }
{ "_id" : "vcQZ2S4MXHs49BknJ", "name" : "Lasgagna", "calories" : "150", "eatenAt" : ISODate("2015-05-20T07:07:00Z"), "userId" : "movpJRhRMwyMZDBqf", "author" : "sergiotapia" }
{ "_id" : "oqw4HZ5tybBKfMJmj", "name" : "test", "calories" : "900", "eatenAt" : ISODate("2015-05-20T07:38:00Z"), "userId" : "movpJRhRMwyMZDBqf", "author" : "sergiotapia" }
{ "_id" : "Pq6vawvTnXQniBvMZ", "name" : "booya", "calories" : "1000", "eatenAt" : ISODate("2015-05-19T07:37:00Z"), "userId" : "movpJRhRMwyMZDBqf", "author" : "sergiotapia" }

我想使用 ISODate 值按日期和时间过滤这些记录。例如,获取 1 月 1 日到 1 月 12 日上午 9 点到下午 2 点之间的记录。

是否可以使用单个字段,还是我需要专门为时间设置一个单独的字段?

【问题讨论】:

    标签: mongodb date meteor


    【解决方案1】:

    您的查询基本上是:

    查找介于 2015 年 1 月 1 日和 2015 年 1 月 12 日之间且时间介于 09:00 和 14:00 之间的文档。

    一种方法是使用 aggregation framework,尤其是 Date Aggregation Operators。您可以使用为 Meteor 添加适当聚合支持的 meteorhacks:aggregate 包。这个包在Mongo.Collection 实例上公开了.aggregate 方法。

    添加到您的应用中

    meteor add meteorhacks:aggregate
    

    然后只需使用.aggregate 函数,如下所示。

    var meals = new Mongo.Collection('meals');
    var pipeline = [
        {
            "$project": {
                "year": { "$year": "$eatenAt" },
                "month": { "$month": "$eatenAt" },
                "day": { "$dayOfMonth": "$eatenAt" },
                "hour": { "$hour": "$eatenAt" },        
                "name" : 1,
                "calories" : 1,
                "eatenAt" : 1,
                "userId" : 1,
                "author" : 1
            }
        },
        {
            "$match": {
                "year": 2015,
                "month": 1,
                "day": { "$gte": 1, "$lte": 12 },
                "hour": { "$gt": 8, "$lt": 14 }
            }
        }
    ];
    
    var result = meals.aggregate(pipeline);
    

    【讨论】:

    • 我需要在哪里放置此代码?我只看了它的服务器,但我不知道它应该在哪里做
    • 如果是服务器端,则只需调用db.meals.aggregate(pipeline),其中pipeline 是上述包含聚合管道的变量。
    • 一个小问题,一旦我调用了这个服务器端方法并获得了正确的数据,如何将它应用到它当前运行的模板上?
    • @Serg 现在您可以在模板函数中使用上面的代码,确保通过meteor add meteorhacks:aggregate 将包添加到您的应用程序中。由于上下文非常广泛,我无法详细说明,但这是上面的一般概念。有关详细信息,请参阅此answer
    猜你喜欢
    • 2022-07-16
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2023-03-23
    • 2018-03-22
    • 2013-10-20
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多