英文:
mgo time.Time or boolean check
问题
我有一个Mongo文档,其中包含一个日期字段,该字段可以是false(或未定义),我似乎找不到如何在golang/mgo中检查字段是否可用、是否为false或是否为日期(time.Time)的方法。
英文:
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
答案1
得分: 2
如果你有一个time.Time
字段,并且想知道它是否被正确设置为有效的日期,你可以查询它的IsZero()
方法。否则,如果你想查询数据库中是否存在这样的文档,你可以采取以下方法之一。
查询字段是否为false:
iter := collection.Find(bson.M{"field": false}).Iter()
查询字段是否存在,可以使用$exists操作符:
iter := collection.Find(bson.M{"field": bson.M{"$exists": true}}).Iter()
查询字段是否为日期类型,可以使用$type操作符:
iter := collection.Find(bson.M{"field": bson.M{"$type": 9}}).Iter()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论