在 MongoDB 正则表达式/PCRE 中转义方括号

Escaping a square bracket in a MongoDB regex / PCRE

我需要在 MongoDB 数据库中查询字段 x[text 开头的文档。我尝试了以下内容: db.collection.find({x:{$regex:/^[text/}}) 失败是因为 [ 是正则表达式语法的一部分。所以我花了一些时间试图找到如何从我的正则表达式中转义 [ ......到目前为止没有任何成功。

感谢任何帮助,谢谢!

在方括号前使用反斜杠 \ 如下:

db.collection.find({"x":{"$regex":"\[text"}})
db.collection.find({"x":{"$regex":"^\[text"}})

db.collection.find({"x":{"$regex":"\\[text"}})
db.collection.find({"x":{"$regex":"^\\[text"}})

return是那些以[text开头的文档

例如:

文档中包含以下数据

{ "_id" : ObjectId("55644128dd771680e5e5f094"), "x" : "[text" }
{ "_id" : ObjectId("556448d1dd771680e5e5f099"), "x" : "[text sd asd " }
{ "_id" : ObjectId("55644a06dd771680e5e5f09a"), "x" : "new text" }

并使用 db.collection.find({"x":{"$regex":"\[text"}}) 它 return 以下结果:

{ "_id" : ObjectId("55644128dd771680e5e5f094"), "x" : "[text" }
{ "_id" : ObjectId("556448d1dd771680e5e5f099"), "x" : "[text sd asd " }