Question

I have a mongo document which contains a date field which can also be false (or not defined), and I can't seem to find how to check if the field is available OR is false OR is a date (time.Time) in golang/mgo :S

Was it helpful?

Solution

If you have a time.Time field, and want to know whether it was properly set with a valid date, you can query its IsZero() method. Otherwise, if you're trying to query the database for such a document, you can do one of the following.

Query if the field is false:

iter := collection.Find(bson.M{"field": false}).Iter()

Query if the field is available, with the $exists operator:

iter := collection.Find(bson.M{"field": bson.M{"$exists": true}}).Iter()

Query if the field is a date, using the $type operator:

iter := collection.Find(bson.M{"field": bson.M{"$type": 9}}).Iter()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top