$regex 在 mongodb 中查找包含字符串的文档
$regex to find a document in mongodb that contains a string
我正在 mongo
中进行数据库查询,我需要通过正则表达式 string
字段(fieldToQuery)查询文档。
数据结构就像
{
fieldToQuery : "4052577300",
someOtherField : "some value",
...
...
}
我有像 "804052577300"
这样的值,我必须使用它来查询上述文档。
如何使用 $regex 运算符实现同样的效果?
更新:
我需要以 regex in mongo
结尾。
你可以这样做:
db.collection.find({ fieldToQuery: /4052577300$/})
上面的正则表达式模式等同于SQL的LIKE操作:
select * from table where fieldToQuery like '%4052577300' => will return the document with the value "804052577300"
您可以执行一种反向正则表达式查询,您可以使用 fieldToQuery
值创建一个正则表达式,然后根据您的查询值对其进行测试:
var value = "804052577300";
db.test.find({
$where: "new RegExp(this.fieldToQuery + '$').test('" + value + "');"
});
$where
运算符允许您对集合中的每个文档执行任意 JavaScript;其中 this
为当前文档,表达式的真值决定该文档是否应该被包含在结果集中。
因此在这种情况下,为每个文档的 fieldToQuery
字段构建一个新的 RegExp
,并在末尾添加 $
以将搜索锚定到字符串的末尾。然后调用正则表达式的 test
方法来测试 value
字符串是否与正则表达式匹配。
$where
字符串在服务器端求值,因此 value
的值必须在客户端求值,方法是直接将其值包含到 $where
字符串中。
请注意,$where
查询可能会非常慢,因为它们不能使用索引。
我正在 mongo
中进行数据库查询,我需要通过正则表达式 string
字段(fieldToQuery)查询文档。
数据结构就像
{
fieldToQuery : "4052577300",
someOtherField : "some value",
...
...
}
我有像 "804052577300"
这样的值,我必须使用它来查询上述文档。
如何使用 $regex 运算符实现同样的效果?
更新:
我需要以 regex in mongo
结尾。
你可以这样做:
db.collection.find({ fieldToQuery: /4052577300$/})
上面的正则表达式模式等同于SQL的LIKE操作:
select * from table where fieldToQuery like '%4052577300' => will return the document with the value "804052577300"
您可以执行一种反向正则表达式查询,您可以使用 fieldToQuery
值创建一个正则表达式,然后根据您的查询值对其进行测试:
var value = "804052577300";
db.test.find({
$where: "new RegExp(this.fieldToQuery + '$').test('" + value + "');"
});
$where
运算符允许您对集合中的每个文档执行任意 JavaScript;其中 this
为当前文档,表达式的真值决定该文档是否应该被包含在结果集中。
因此在这种情况下,为每个文档的 fieldToQuery
字段构建一个新的 RegExp
,并在末尾添加 $
以将搜索锚定到字符串的末尾。然后调用正则表达式的 test
方法来测试 value
字符串是否与正则表达式匹配。
$where
字符串在服务器端求值,因此 value
的值必须在客户端求值,方法是直接将其值包含到 $where
字符串中。
请注意,$where
查询可能会非常慢,因为它们不能使用索引。