假设我有一个这样的集合:
{
"id": "2902-48239-42389-83294",
"data": {
"location": [
{
"country": "Italy",
"city": "Rome"
}
],
"time": [
{
"timestamp": "1626298659",
"data":"2020-12-24 09:42:30"
}
],
"details": [
{
"timestamp": "1626298659",
"data": {
"url": "https://example.com",
"name": "John Doe",
"email": "john@doe.com"
}
},
{
"timestamp": "1626298652",
"data": {
"url": "https://www.myexample.com",
"name": "John Doe",
"email": "doe@john.com"
}
},
{
"timestamp": "1626298652",
"data": {
"url": "http://example.com/sub/directory",
"name": "John Doe",
"email": "doe@johnson.com"
}
}
]
}
}
现在主要关注子文档数组(“data.details”):我只想获得相关匹配的输出,例如:
db.info.find({"data.details.data.url": "example.com"})
如何获得包含“example.com”但不与“myexample.com”匹配的所有“data.details.data.url”的匹配项。 当我用 $regex 执行时,我得到的结果太多,所以如果我查询“example.com”,它也会返回“myexample.com”
即使我确实得到了部分结果(使用 $match),它也很慢。我试过这个聚合阶段:
{ $unwind: "$data.details" },
{
$match: {
"data.details.data.url": /.*example.com.*/,
},
},
{
$project: {
id: 1,
"data.details.data.url": 1,
"data.details.data.email": 1,
},
},
我真的不明白这个模式,使用 $match,有时 Mongo 确实可以识别前缀,如“https://”或“https://www”。有时不会。
更多信息: 我的收藏有几十GB,我创建了两个索引:
它确实提高了查询性能,但还不够,我仍然遇到 $match 与 $regex 的问题。感谢帮助!
答案 0 :(得分:0)
您的错误在于正则表达式。它匹配所有 URL,因为子字符串 example.com 在所有 URL 中。例如:https://www.myexample.com 匹配粗体部分。
为避免这种情况,您必须使用另一个正则表达式,例如,以该域开头。
例如:
(http[s]?:\/\/|www\.)YOUR_SEARCH
将检查您要搜索的内容是否位于 http:// 或 www 后面。分数。 https://regex101.com/r/M4OLw1/1
我把完整的查询留给你。
[
{
'$unwind': {
'path': '$data.details'
}
}, {
'$match': {
'data.details.data.url': /(http[s]?:\/\/|www\.)example\.com/)
}
}
]
注意:您必须对正则表达式中的特殊字符进行转义。点匹配任何字符,斜线将关闭正则表达式,导致错误。