我试图找到person
number
在其中'-'
或'.'
的所有lists
。我已经尝试过这个答案,但它不适用于数组中的元素。
但是当我尝试通过整个字符串查找时,如果没有regex
符号,就会找到文档。
每个示例:
db.getCollection('list').find({"persons.number": "123456789"}) //works!
db.getCollection('list').find({"persons.number": /3/}) //not work...
db.getCollection('list').find({"persons.number": /.*3.*/}) //not work
db.getCollection('list').find({"persons.number": /.*..*/}) //not work
db.getCollection('list').find({"persons.number": /.*[-.]+.*/}) //not work
如果我尝试通过数组之外的某个属性(每个示例中list
的属性(查找文档,则/3/
、/.*3.*/
和/.*[-.]+.*/
工作。
文档格式:
{
"_id" : ObjectId("5af3037ee8006c4a04e84b2f"),
"id" : 1,
"persons" : [
{
"id" : 1,
"number" : "123.123.123-22"
},
{
"id" : 2,
"number" : "123.456.789-11"
}
]
}
那么,有哪些选择呢?
我正在使用Azure的MongoDB。在控制台上执行db.version()
将返回3.2.0
。
正则表达式.*[-.]+.*
应该可以工作,
试试这个,
db.getCollection('list').find({"persons.number": /.*[-.]+.*/})
对于搜索多个模式,即模式的OR,正则表达式格式几乎没有什么不同。
(pattern1)|(pattern2)
在我的本地运行的 3.4.6 上尝试了以下 mongo 查询,但它也应该适用于 3.2.x
db.list.aggregate([{"$unwind":{"path":"$persons"}},{"$project":{"_id":1,"persons.number":1}},{"$match":{"persons.number":{"$regex":/.*(.)|(-).*/}}},{"$group":{_id:"$_id"}}])