So I have a very Simple Struct which is persisted in the MongoDB
type Test struct {
ID string `bson:"_id"`
Status string `bson:"status"`
TestTime time.Time `bson:"TestTime"`
}
While Retrieving I want to make sure that I am not retrieving any value whose TestTime is not initialized i.e exclude missing/zero equivalent value of time.Time
filter := bson.M{"status": "Ready"}
Any advice on how should I update my filter criteria here
cursor, err := r.store.Db.Collection("testCollection").Find(ctx, filter)
if err != nil {
return err
}
err = cursor.All(ctx, result)
if err != nil {
return err
}
return nil
}
It depends on how you inserted your documents into MongoDB.
If you inserted them using your Test struct where you did not change the TestTime field, that means it will have the zero value of time.Time, which will get saved into MongoDB. In MongoDB it has a value of:
TestTime: ISODate("0001-01-01T00:00:00.000Z")
To filter out such times, in Go again use the zero value of time.Time like this:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{"$ne": time.Time{}},
}
If you inserted documents in some other way where TestTime may be null or non-existing, you may account for that like this:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{
"$nin": []any{time.Time{}, nil},
},
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With