基本日期之间查询 $gte、$lte 等

2024-02-19

我在 mongo 查询的正确时间格式方面遇到问题。

我的问题是:

  • Is time.Timemongo ISODate 对象的正确 go 类型?
  • 为什么我的时间解析似乎解析完全不同的日期?

这是我正在做的事情的完整示例。

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 包的 API 文档解释了您应该了解的大部分内容。最重要的是 Go 类型按照您期望的方式映射到它们的 bson 等价物。 Bson 日期映射到 time.Time。

使用你的例子:

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

where fromDate and toDate are time.Time values.

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

query:=bson.M{"field":bson.M{"$in":[]string{"value1","value2"}}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基本日期之间查询 $gte、$lte 等 的相关文章

  • 无需时间即可生成随机字符串?

    我知道如何使用 Runes 和播种 rand Init 在 go 中生成随机字符串time UnixNano 我的问题是 是否可以 使用 stdlib 在不使用当前时间戳 安全 的情况下播种 rand 此外 我问 因为仅仅依靠时间来为敏感操
  • 有没有一种方法可以在不停机的情况下更新 net/http 服务器中的 TLS 证书?

    我有一个简单的 https 服务器 提供一个简单的页面 如下所示 为简洁起见 没有错误处理 package main import crypto tls fmt net http func main mux http NewServeMux
  • 无法安装js-bson

    我正在使用Windows 7 64位 尝试安装bson作为mongodb的依赖项 我收到此错误 npm WARN package json email protected cdn cgi l email protection No READ
  • Express js 错误:“express 已弃用 res.sendfile:请改用 res.sendFile”

    设置路径的正确方法是什么 在我的应用程序中 我使用此代码设置发送文件的路径 app get function req res get put post delete res sendfile dirname client views ind
  • Go中如何从json字符串中获取键值

    我想尝试从 Go 中的 JSON 获取键值 但我不确定如何操作 我已经能够使用 simplejson 读取 json 值 但是我无法找到如何获取键值 有人能指出我正确的方向和 或帮助我吗 谢谢你 您可以通过执行以下操作来获取 JSON 结构
  • 将字符串数组转换为对象 Id 数组

    我有一个字符串数组 let stringObjectIdArray fssdlfsd343 43434234242 342424242 我想使用 mongoose 类型将字符串数组更改为对象 Id 数组 但它不起作用 它仅适用于字符串而不是
  • 显示来自 mongodb 的所有数据并在 doT.js 模板引擎中渲染它

    我想从 mongodb 中提取数据并将其传递给视图 一切似乎都正常 但我没有看到所有 10000 条记录都显示出来 而是只看到了一条 我觉得我非常接近解决它 但我陷入困境 我正在使用node mongodb native express和d
  • 如何对 mongodb/mongoid 脚本进行基准测试,以比较两种不同的查询技术

    您对如何测试两种不同的 mongoid mongodb 查询实现的性能有什么建议吗 要比较的实现与以前的相关 问答 https stackoverflow com questions 10121977 extracting modellin
  • 检查值是否实现接口的说明

    我读过 Effective Go 和其他类似这样的问答 golang接口合规性编译类型检查 https stackoverflow com questions 17994519 golang interface compliance com
  • mocha——手表和猫鼬模型

    如果我让 mocha 监视更改 每次保存文件时 mongoose 都会抛出以下错误 OverwriteModelError 无法覆盖Client模型一旦编译 我知道猫鼬不允许两次定义模型 但我不知道如何让它与mocha watch clie
  • Inno Setup安装先决条件[重复]

    这个问题在这里已经有答案了 我正在通过 Inno Setup 创建一个安装程序 我看到很多关于如何检测先决条件是否存在的代码示例 但没有任何关于当我找不到先决条件时如何实际安装先决条件的代码示例 我确信它非常简单 但是我该如何安装先决条件呢
  • 当涉及多个渠道时,select 如何工作?

    我发现在多个非缓冲通道上使用 select 时 例如 select case lt chana case lt chanb 即使两个通道都有数据 但在处理此选择时 case chana 和 case chanb 的跟注不平衡 package
  • 在 Go 中跟踪 HTTP 请求时指定超时

    我知道通过执行以下操作来指定 HTTP 请求超时的常用方法 httpClient http Client Timeout time Duration 5 time Second 但是 我似乎不知道在跟踪 HTTP 请求时如何执行相同的操作
  • 我可以要求在 mongodb 集合中设置属性吗? (不为空)

    我可以在 mongodb 中定义一个需要设置某些属性的模式吗 很像NOT NULL在 SQL 中 如果可以的话 这个的语法是什么 我正在使用 Node js 和猫鼬 猫鼬 v3 6 15 MongoDB v2 4 5 EditCharles
  • MongoDB $orderby 和 Sort 之间的区别

    我想获取最新的文档 这显然是一个文档 因此findOne应该可以正常工作 但findOne这里返回插入的第一个文档 所以我现在有两个选择要么使用 orderBy with findOne or use sort 功能与 limit in f
  • Node.js 重用 MongoDB 参考

    我无法理解 Node js 例如 MongoDB 访问 这是我得到的 mydb js var mongodb require mongodb server new mongodb Server staff mongohq com 10030
  • Mongodb聚合数组大小大于匹配项[重复]

    这个问题在这里已经有答案了 我有一个集合 其中投资是 mongodb 文档内的一个数组 现在使用聚合 我尝试过滤投资长度超过 5 倍的结果 然后使用匹配查询进行下一步处理 Collection id 000000 investments h
  • 如何在特定文件夹中运行 shell 命令

    我可以用这个out err exec Command git log Output 获取将在与可执行位置相同的路径中运行的命令的输出 如何指定要在哪个文件夹中运行命令 exec Command https golang org pkg os
  • MONGODB [DEBUG] 游标的cursor.refresh() 7078636577051629992

    更新大型 json 列表时 出现以下错误 2012 04 01T09 34 00 00 00 app run 1 MONGODB DEBUG cursor refresh for cursor 7078636577051629992 201
  • Mongo按动态字段排序

    所以我传入了一个动态变量 它是我想要排序的字段的名称 假设下面的 sortVariable 可能等于 price createdAt name 等 这不起作用 我该怎么做 function findStuff sortVariable va

随机推荐