3

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
   }
icza
  • 389,944
  • 63
  • 907
  • 827
EagerLearner
  • 447
  • 1
  • 5
  • 11
  • You can specify `{ testTime: { $ne: null } }`, `{ testTime: { $exists: true } }` filters to check the field value is not null or the field exists. – prasad_ Aug 10 '22 at 03:21

1 Answers1

2

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},
    },
}
icza
  • 389,944
  • 63
  • 907
  • 827