Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check zero Equivalent of time.Time when retrieving from mongodb Golang

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
   }
like image 224
EagerLearner Avatar asked Nov 15 '25 19:11

EagerLearner


1 Answers

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},
    },
}
like image 110
icza Avatar answered Nov 17 '25 18:11

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!