Mongodb中如何按年龄查询?

发布于 2024-11-09 11:32:54 字数 75 浏览 11 评论 0原文

如果我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

追风人 2024-11-16 11:32:54

您可以将 DOB 日期存储为 ISO 格式 - yyyymmdd - 作为一个简单的数字,即

db.col.insert( { dob: 19910412 } )
db.col.insert( { dob: 19900708 } )
db.col.insert( { dob: 19880511 } )
db.col.insert( { dob: 19870225 } )

然后,要查找特定日期之前的所有日期,请执行以下操作:

db.col.find( { dob: { $lt: 19900101 } } )

向此字段添加索引将加快这些查询的速度:

db.col.ensureIndex( { dob: 1 } )

You can store your DOB dates in ISO format - yyyymmdd - as a simple number, i.e.

db.col.insert( { dob: 19910412 } )
db.col.insert( { dob: 19900708 } )
db.col.insert( { dob: 19880511 } )
db.col.insert( { dob: 19870225 } )

Then, to find all the dates before a particular date, do this:

db.col.find( { dob: { $lt: 19900101 } } )

Adding an index to this field will speed up these queries:

db.col.ensureIndex( { dob: 1 } )
拥有 2024-11-16 11:32:54

将数据存储为 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.

眉目亦如画i 2024-11-16 11:32:54

我建议存储“真实”日期对象而不是字符串。然后您可以使用常用的比较运算符。如果你不能这样做,另一种方法是存储年龄整数。后者不太有用,因为它必须每年更新,但值得考虑。

编辑:允许您使用现有数据的另一种方法是将匹配函数传递给collection.find()。显然,这会对性能产生影响,因为必须为集合中的每个对象评估该函数。请参阅 $where 文档。例如...

var date =  function() {
    return new Date(this.dob) < new Date('1/1/1990');
}

db.mycollection.find(date);

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...

var date =  function() {
    return new Date(this.dob) < new Date('1/1/1990');
}

db.mycollection.find(date);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文