mgo时间.Time或布尔值检查

huangapple go评论73阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2013年9月10日 22:35:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/18721801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定