简体   繁体   English

如何在mongodb ObjectId字段上进行正则表达式查询

[英]how to do a regex query on mongodb ObjectId field

this is a bit tricky.. how do you do a regex query on the ObjectId field? 这有点棘手..你如何在ObjectId字段上进行正则表达式查询?

i'm using the java api, so this is what i have so far 我正在使用java api,所以这就是我到目前为止所拥有的

BasicDBObject q = new BasicDBObject()
q.put(field, Pattern.compile(value, Pattern.CASE_INSENSITIVE));

this works fine for any regular field. 这适用于任何常规字段。 but doesn't seem to work with ObjectId field. 但似乎不适用于ObjectId字段。 which i assume is because i can't compare an ObjectId to a string? 我假设是因为我无法将ObjectId与字符串进行比较? and i can't exactly just put a partial id or a regex into a new ObjectId. 并且我不能完全将部分id或正则表达式放入新的ObjectId中。 it'll just throw an error. 它只会抛出一个错误。

any ideas on this? 有什么想法吗? i'm trying to give users a way to enter part of an id, and be able to get back all documents with that pattern. 我正在尝试为用户提供一种输入id的一部分的方法,并能够使用该模式获取所有文档。

thanks in advance! 提前致谢!

As far as I know ObjectId is a own type in MongoDB and does not behave like a string. 据我所知,ObjectId在MongoDB中是一个自己的类型,并且不像字符串。 And although there are other types in MongoDB distinct from string, like arrays and so on, which are searchable by a regex pattern, this seems not possible for ObjectId. 虽然MongoDB中的其他类型不同于字符串,如数组等,可以通过正则表达式模式进行搜索,但对于ObjectId来说这似乎是不可能的。 To implement an id search like yours I would probably define an own, indexed id field which contains an id as a simple string and cold-shoulder ObjectId. 要实现像你这样的id搜索,我可能会定义一个自己的索引id字段,其中包含一个id作为一个简单的字符串和冷漠的ObjectId。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM