日期之间的基本查询$ gte,$ lte等 [英] Basic between dates queries $gte, $lte, etc

查看:145
本文介绍了日期之间的基本查询$ gte,$ lte等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mongo查询的时间格式设置有问题.

I'm having an issue with correct time formatting for my mongo query.

我的问题是这些:

  • time.Time 是mongo ISODate对象的正确选择吗?
  • 为什么我的时间解析似乎要解析一个完全不同的日期?
  • Is time.Time the right go type for mongo ISODate object?
  • Why is my time parsing seeming to parse a completely different date?

这是我要做什么的完整例子.

Here's a complete example of what i've got going.

package main

import (
    // "fmt"
    "context"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// Here's a JSON of the record as it is in the db
// { 
//  "_id" : ObjectId("5fa467af036d5f46914c423c"), 
//  "subscriptionRuleId" : "email@email", 
//  "eventDateTime" : ISODate("2020-11-05T20:59:27.096+0000"), 
//  "eventType" : "string-with-event-type", 
//  "passportAtlas" : "a long string", 
//  "_class" : "com.proj.info.model.dto.EventLog"
// }

type eventLog struct {
    SubscriptionRuleID string `json:"subscriptionRuleId,omitempty" bson:"subscriptionRuleId"`
    EventType string `json:"eventType" bson:"eventType"`
    EventDateTime time.Time `json:"eventDateTime" bson:"eventDateTime"`
    PassportAtlas string `json:"passportAtlas" bson:"passportAtlas`
}

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx, clientOptions)

    if err != nil { log.Fatal(err) }

    err = client.Ping(ctx, nil)

    if err != nil { log.Fatal(err) }

    collection := client.Database("compose").Collection("eventLog")

    df := "2006-02-04"
    dateFrom, _ := time.Parse(df, "2020-11-20")
    dateTo, _ := time.Parse(df, "2020-11-21")

    // This does not seem to work. 
    // A log of the dates gives me the wrong dates

    log.Printf("\nFROM: %v\nTO: %v", dateFrom, dateTo)
    // OUTPUTS:
    // FROM: 2020-01-09 00:20:00 +0000 UTC
    // TO: 2020-01-10 00:21:00 +0000 UTC

    // Notice the dates are formatted wrong in the log.
    // Even though the dates are wrong, I would still match
    // Records with those wrong dates as i've got tens of thousands
    // over the last few years...
 
    query := bson.M{
        "eventDateTime": bson.M{
            "$gte": dateFrom,
            "$lt": dateTo,
        },
    }

    cur, err := collection.Find(ctx, query)

    if err != nil { log.Fatal(err) }

    defer cur.Close(context.Background())

    var eventLogs []eventLog

    for cur.Next(ctx) {
        var eventLog eventLog
        cur.Decode(&eventLog)
        eventLogs = append(eventLogs, eventLog)
    }

    if err := cur.Err(); err != nil { log.Fatal(err) }

    log.Printf("num records: %v", len(eventLogs))
}

推荐答案

BSON只是二进制JSON.MongoDB查询是BSON文档,它使用类似的结构,通过使用 bson.M (它是map [string] interface {})来处理对象和数组的值切片.还有一个 bson.D 类型,可用于构造保留其字段顺序的对象.

BSON is simply binary JSON. MongoDB queries are BSON document constructed using similar constructs, by using bson.M (which is a map[string]interface{}) for objects and slices of values for arrays. There is also a bson.D type that can be used to construct objects that preserve ordering of its fields.

API文档解释了您应该了解的大多数内容.最重要的是,Go类型按照您期望的方式映射到其bson等效项.Bson日期会映射到time.Time.

API documentation for the bson package explains most of the things you should know. The most important thing is that Go types are mapped to their bson equivalents in the way you expect them. Bson dates map to time.Time.

使用您的示例:

query:=bson.M{"eventDateTime":bson.M{"$gte": fromDate, "$lt":toDate}}

其中 fromDate toDate time.Time 值.

再举一个例子,一个$ in查询可以写成:

As another example, an $in query can be written as:

query:=bson.M{"field":bson.M{"$in":[]string{"value1","value2"}}}

这篇关于日期之间的基本查询$ gte,$ lte等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆