【问题标题】:How to check if a record exists with golang and the offical mongo driver如何使用 golang 和官方 mongo 驱动程序检查记录是否存在
【发布时间】:2020-10-12 21:53:33
【问题描述】:

我在 golang 中使用官方的 mongo 驱动程序,并试图确定是否存在记录。不幸的是,文档没有解释如何做到这一点。我正在尝试使用 FindOne 执行此操作,但是当找不到结果时它会返回并出错,而且我不知道如何将该错误与任何其他错误区分开来(缺少比较感觉错误的字符串。什么是正确的方法使用官方 golang 驱动检查 mongo 中是否存在文档?

这是我的代码。

ctx := context.Background()
var result Page

err := c.FindOne(ctx, bson.D{{"url", url}}).Decode(&result)

fmt.Println("err: ", err)

// how do I distinguish which error type here?
if err != nil {
    log.Fatal(err)
}

【问题讨论】:

标签: mongodb go


【解决方案1】:

这就是答案。

var coll *mongo.Collection
var id primitive.ObjectID

// find the document for which the _id field matches id
// specify the Sort option to sort the documents by age
// the first document in the sorted order will be returned
opts := options.FindOne().SetSort(bson.D{{"age", 1}})
var result bson.M
err := coll.FindOne(context.TODO(), bson.D{{"_id", id}}, opts).Decode(&result)
if err != nil {
    // ErrNoDocuments means that the filter did not match any documents in the collection
    if err == mongo.ErrNoDocuments {
        return
    }
    log.Fatal(err)
}
fmt.Printf("found document %v", result)

【讨论】:

  • 在不解组 BSON 字节的情况下,当文档不存在时,调用 Err() 而不是 Decode() 就足够了
猜你喜欢
  • 1970-01-01
  • 2019-09-07
  • 2015-12-07
  • 2020-09-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多