0

MongoDB 2.4.6 的 Regex find 的行为方式与 Java Pattern 类不同。谁能解释为什么?

在 MongoDB 中插入数据:

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

查找所有项目:

db.Project.find()

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

查找名称为“t”的所有项目:

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

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

检查唯一的项目名称与正则表达式“t”不匹配:

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

如您所见,正则表达式 db.Project.find 返回一个名称不是“t”但包含“t”的项目。我错过了什么?

谢谢!

4

1 回答 1

2

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'}

于 2013-11-07T03:44:35.310 回答