简体   繁体   中英

MongoDB find with regex behaves differently from Java

Regex find with MongoDB 2.4.6 is not behaving the same way as the Java Pattern class does. Can anyone explain why?

Inserting data in MongoDB:

db.Project.insert({ "_id" : "e0b57d9e-744c-471e-ae95-22a389d2988d", "name" : "Project.20131106101344433" });

Finding all Projects:

db.Project.find()

{
    "_id" : "e0b57d9e-744c-471e-ae95-22a389d2988d",
    "name" : "Project.20131106101344433"
}

Finding all Projects whose name is "t":

db.Project.find({"name" : /t/})

{
    "_id" : "e0b57d9e-744c-471e-ae95-22a389d2988d",
    "name" : "Project.20131106101344433"
}

Checking that sole Project name does not match regex "t":

@Test
public void regex() {
    assertTrue(!Pattern.matches("t", "Project.20131106101344433"));
}

As you see, the regex db.Project.find returns a Project whose name is not "t", but does contain "t". What am I missing?

Thanks!

In this case db.Project.find({"name" : /t/}) you are not looking for a document whose name is t , you are looking for every document whose name contains t . You can read about PECL here and test what are you doing here .

To find exact match you have to do {"name" : 't'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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