User1789
User1789

Reputation: 31

Checking if data exists in a mongodb collection in goLang?

If i want to check if there currently exists at least one document in a collection, how would I go about doing this in GoLang?

Upvotes: 0

Views: 6359

Answers (1)

Nic Raboy
Nic Raboy

Reputation: 3153

The most performant way to check if documents exist in a collection is to use the EstimatedDocumentCount function on a collection because it gets an estimate from the collection's metadata.

You can do something like this:

count, err := collection.EstimatedDocumentCount(context.Background())

If the actual count of documents in the collection is important and you need more than just an estimate, it makes sense to look into the MongoDB aggregation framework.

You can do something like this which wraps the aggregation framework:

count, err := collection.CountDocuments(ctx, bson.M{})
if err != nil {
    panic(err)
}
if count >= 1 {
    fmt.Println("Documents exist in this collection!")
}

You could also try something like the following if you want to use the aggregation framework directly:

cursor, err := episodesCollection.Aggregate(ctx, []bson.D{
    bson.D{{"$count", "mycount"}},
})
if err != nil {
    panic(err)
}
var counts []bson.M
cursor.All(ctx, &counts)
fmt.Println(counts[0]["mycount"])

Upvotes: 1

Related Questions