如何使用 golang 和官方 mongo 驱动程序检查记录是否存在

jsh*_*hen 1 go mongodb

我在 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)
}
Run Code Online (Sandbox Code Playgroud)

jsh*_*hen 5

这是答案。

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)
Run Code Online (Sandbox Code Playgroud)