【问题标题】:How to write mongodb shell query into golang如何将 mongodb shell 查询写入 golang
【发布时间】:2021-06-11 04:10:29
【问题描述】:

我有一个我为 shell 编写的 mongodb 查询,它工作正常,但现在我想将它转移到 golang 下面是我尝试过的查询和解决方案

db.getCollection('test').find({"course" : /^ba$/i, "status":{"$ne":0}}).count()

我试过了:-

query := bson.M{"status": bson.M{"$ne": 0}, "course": "/^" + parameter + "$/i"}
query := bson.M{"status": bson.M{"$ne": 0}, "course": `/^` + parameter + `$/i`}

但工作不正常,谁能找到我正在做的错误。

【问题讨论】:

  • @NobbyNobbs 我如何提到我需要在这个bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}中搜索的值
  • 我想像bson.D{{"course", primitive.Regex{Pattern: "^" + parameter + "$", Options: "i"}}

标签: regex mongodb go


【解决方案1】:

这是您可以通过 golang mongodb 驱动程序计算文档和使用正则表达式的方法。


pattern := "test"
count, err := coll.CountDocuments(ctx, bson.D{
    {"course", primitive.Regex{Pattern: "^" + pattern + "$", Options: "i"}},
    {"status", bson.D{{"$ne", 0}}},
})
if err != nil {
    panic(err)
}
fmt.Println(count)

【讨论】:

  • 这将导致 null
  • @PuneetJindal 这可能返回零但不返回 null。这是一个有效的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多