[英]MongoDB query to find documents with variations
示例MongoDB文档:
{
name: "something"
product: "ABC-123"
}
问题是产品可能并不总是遵循相同的命名约定。 它可以是以下任何一种
"ABC-123"
"ABC123"
"ABC 123"
因此,如果我搜索“ABC-123”,我希望任何文档都可以匹配,无论命名约定如何变化。
编辑:您可以使用表达式^ABC(?:.*?)\\\\d+$
在查询中使用$ regex ,如下所示:
示例MongoDB文档:
db={
"products": [
{
"name": "product A",
"product": "ABC-123"
},
{
"name": "product B",
"product": "ABC123"
},
{
"name": "product C",
"product": "ABC-123"
}
]
}
查询:
db.products.find({
"product": {
"$regex": "^ABC(?:.*?)\\d+$"
}
})
演示: https : //mongoplayground.net/p/WdqTg7LCZIk
我们或许可以找到这个问题的表达式。 也许,让我们从类似于以下的表达式开始:
product:\s+"(.+?)"
在这里,我们使用product:\\s+"
作为左边界,然后我们收集任何字符,然后我们将它从右边绑定"
。
const regex = /product:\\s+"(.+?)"/gm; const str = `{ name: "something" product: "ABC-123" }`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
或者我们可以将它扩展到我们想要捕获的内容而不是捕获:
(?:product:\s+")(.+?)(?:")
如果您的变化只是那个而且那些是您的3种可能性,那么Emma的答案正是您所需要的。 如果正则表达式失控并且您最终有很多不同的产品变体 ,那么另一种选择是$ text search / index AND regEx。
例如:
db.getCollection('COLNAME').find({
$or: [
{
$text: {$search: 'abc'} // By default it is case insensitive
},
{
product: {"$regex": "YOUR_REGEX_HERE"}
}
]
})
这也是高效的,因为你会在product
和常规索引上有文本索引。 这也可以处理像XXX-ABC
这样的情况以及您可能不知道/不具备的任何其他变体。 所以要考虑一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.