Mongodb中如何按年龄查询?
如果我在MongoDB中有一个dob(出生日期)字段,我如何查询出生日期小于1/1/1990(它是一个字符串)或小于某个年龄的所有记录?
If I have a dob (date of birth) field in MongoDB, how can I query all records where date of birth is less than 1/1/1990 (it's a string) or less than a certain age?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 DOB 日期存储为 ISO 格式 - yyyymmdd - 作为一个简单的数字,即
然后,要查找特定日期之前的所有日期,请执行以下操作:
向此字段添加索引将加快这些查询的速度:
You can store your DOB dates in ISO format - yyyymmdd - as a simple number, i.e.
Then, to find all the dates before a particular date, do this:
Adding an index to this field will speed up these queries:
将数据存储为 Date() 对象或 ISO 格式的字符串。在这两种情况下,您都可以使用标准 $gt 或 $lt 运算符。
Either store the data as Date() object or as string in ISO format. In both cases you can use the standard $gt or $lt operators.
我建议存储“真实”日期对象而不是字符串。然后您可以使用常用的比较运算符。如果你不能这样做,另一种方法是存储年龄整数。后者不太有用,因为它必须每年更新,但值得考虑。
编辑:允许您使用现有数据的另一种方法是将匹配函数传递给collection.find()。显然,这会对性能产生影响,因为必须为集合中的每个对象评估该函数。请参阅 $where 文档。例如...
I suggest storing a 'real' date object rather than a string. You may then use the usual comparison operators. If you cannot do that, an alternative would be storing an age integer. The latter is less useful as it must be updated every year but it's worth considering.
EDIT: An alternative that will allow you to work with your existing data would be to pass a match function to collection.find(). Obviously this has performance implications as the function must be evaluated for each object in the collection. See $where docs. For example...