我正在尝试使用用户生成的字符串变量在MongoDB数据库中执行简单的通配符查询。例如,如果用户搜索“Bu”,那么像' Burger'和汉堡王'应该从数据库返回。我搜索并尝试了几件事,但似乎没有任何工作。任何帮助将不胜感激。注意:这是客户端JS。
var text = document.getElementById("Search_Box").value;
var regex = new RegExp(text + ".*");
client.login().then(() => db.collection('businesses')
.find({name:{$regex:regex}}).then(docs => {
console.log("[MongoDB Stitch] Connected to Stitch");
答案 0 :(得分:1)
如果您有以下文件:
{
"_id" : ObjectId("5a0f3a464d8a2fe38bec4e92"),
"name" : "Burger"
}
{
"_id" : ObjectId("5a0f3a464d8a2fe38bec4e94"),
"name" : "Burger King"
}
{
"_id" : ObjectId("5a0f3a464d8a2fe38bec4e96"),
"name" : "Booby's"
}
{
"_id" : ObjectId("5a0f3a464d8a2fe38bec4e98"),
"name" : "McDonald"
}
要获得以“Bu”开头的所有内容,您可以
db.collection('businesses').find({name: {$regex: '^Bu'}})
或
db.collection('businesses').find({name: {$regex: /^Bu/}})
如果您需要在任何地方包含“Ki。* g”的任何内容:
db.collection('businesses').find({name: {$regex: 'Ki.*g'}})
或
db.collection('businesses').find({name: {$regex: /Ki.*g/}})
付出努力并完成文档。一切都在那里解释,有更多的细节。 https://docs.mongodb.com/manual/reference/operator/query/regex/
答案 1 :(得分:-1)
我遇到了类似的问题。我发送:
async search (term) {
this.suggestions = await this.db.collection(this.collection).find({name: {$regex: term + '.*', $options: 'i'}}).sort({'_id': 1}).execute()
}
我从Mongo那里得到了回复
Stack Trace:
StitchError: $regex requires regular expression
at find (<native code>)
at apply (<native code>)
at executeServiceFunction (<anonymous>:10:10)
{
"service": "mongodb-atlas",
"name": "find",
"arguments": [
{
"database": "monsters",
"collection": "monsters",
"query": {
"name": {
"$regex": "Aart.*",
"$options": "i"
}
},
"project": null,
"sort": {
"_id": {
"$numberInt": "1"
}
}
}
]
}