How to check if a record exists with golang and the offical mongo driver

Viewed 8867

I'm using the official mongo driver in golang, and am trying to determine if a record exists. Unfortunately the documentation doesn't explain how to do this. I'm attempting to do it with FindOne, but it returns and error when no results are found, and I don't know how to distinguish that error from any other error (short of comparing strings which feels wrong. What's the right way to check if a document exists in mongo with the official golang driver?

Here's my code.

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)
}
1 Answers

Here's the answer.

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)
Related