How to use MongoRegex (MongoDB C# Driver)

。_饼干妹妹 提交于 2019-12-29 01:52:09

问题


Has anyone have any idea how to use MongoRegex for the document search?

I attempted this, but returns nothing back:

var spec = new Document();
spec.Add("Name", new MongoRegex("/" + searchKey + "*/", "i"));
collection.Find(spec)

Wondering why it doesn't work, I tried to execute following command from the console:

db.things.find({"Name":/john*/i}) /* WORKS */
db.things.find({"Name":"/john*/i"}) /* DOESN'T WORK */

Is that possible that the driver applies double quotation to the regex?

Thanks..


回答1:


you just want a simple prefix query. Your regex is then ^ + searchKey. Also, this form will allow mongodb to use an index on Name.

var spec = new Document("Name", new MongoRegex(string.Format("^{0}",searchKey), "i"));
collection.Find(spec)



回答2:


I think you need to not include the "/"s in C#, i.e.,

spec.Add("Name", new MongoRegex(searchKey + "*", "i"));



回答3:


After digging the source code, I finally found the answer :)

var spec = new Document();
spec.Add("Name", new MongoRegex(".*" + searchKey + ".*", "i"));
collection.Find(spec)


来源:https://stackoverflow.com/questions/2527443/how-to-use-mongoregex-mongodb-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!