由created_at 找到的mongoid 正则表达式不起作用?
我正在使用 mongoid
和 ruby 1.9.3。馆藏有超过1000万条记录。
c = Contact.where(created_at: "2012-02-10 08:49:05 UTC")
c.count
#=> 2
但是,当我使用正则表达式时,找不到记录:
c = Contact.where(created_at: "/.*2012-02-10.*/")
c.count
#=> 0
I'm using mongoid
with ruby 1.9.3. Collection has more than 10 million records.
c = Contact.where(created_at: "2012-02-10 08:49:05 UTC")
c.count
#=> 2
However when I use regular expressions no records are found:
c = Contact.where(created_at: "/.*2012-02-10.*/")
c.count
#=> 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己不使用 Mongoid,但是你确定它在使用
where
查询时支持正则表达式吗?但这应该有效:I don't use Mongoid myself, but are you sure that it supports regex when querying with
where
? This should work though:我不确定 Mongoid 是如何做到这一点的,但是您想要进入 MongoDB 的查询是这样的:
请注意,我们以
$gte
开头,以$lt
结尾获得半开区间[2012-02-10, 2012-02-11)
,这与将完整时间截断为日期部分相同。对于 MongoMapper,我会这样说:
也许同样的事情也适用于 Mongoid。
另外, this:
是一个字符串,您可能需要
/.*2012-02-10.*/
来获取 MongoDB 的正则表达式。这不适用于 MongoMapper,所以我怀疑您暂时也无法在 Mongoid 中使用正则表达式;他们可能只是将此类事情交给较低级别的 MongoDB 连接层。无论如何,您几乎不想在 MongoDB 中使用像这样的正则表达式,因为它无法使用索引,您希望将其锚定在开头,/^2012-02-10/
,以便可以使用索引。I'm not sure how Mongoid does this but the query you want to get down to MongoDB is something like this:
Note that we start with
$gte
and end with$lt
to get the half open interval[2012-02-10, 2012-02-11)
and that's the same as truncating the full time to just the date part.With MongoMapper I'd say this:
Perhaps the same thing will work with Mongoid.
Also, this:
is a string, you probably want
/.*2012-02-10.*/
to get a regex down to MongoDB. That won't work with MongoMapper so I suspect that you won't be able to use a regex for a time with Mongoid either; both of them probably just hand this sort of thing off to the lower level MongoDB connection layer. In any case, you almost never want to use a regex like that with MongoDB as it won't be able to use an index, you'd want to anchor it at the beginning,/^2012-02-10/
, so that indexes could be used.