英文:
How can I implement MongoDB autocomplete in Golang using mongo driver?
问题
我正在尝试在Golang中实现一个自动完成搜索,但是我在语法上一直遇到错误。
contactsCollection := c.DB.Database("XYZ").Collection("contacts")
result, err := contactsCollection.Aggregate([]bson.M{
{
"$search": bson.M{
"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
},
},
},
})
searchQuery
是输入的内容,email
是我想要进行自动完成的字段。我假设我可以返回result
。
我在这里漏掉了什么?
英文:
I am trying to implement a autocomplete search in golang but I keep getting an error with the syntax
contactsCollection := c.DB.Database("XYZ").Collection("contacts")
result, err := contactsCollection.aggregate([{
"$search": {
"autocomplete": {
"query": searchQuery,
"path": "email",
"tokenOrder": "any"
}
}
}
])
searchQuery
is the input coming in and email is the field upon which I want to do the autocomplete. I am assuming that I would be able to return result
.
What am I missing here?
答案1
得分: 1
查看一些关于如何在Go中使用MongoDB客户端的教程或文档。您需要使用bson包来编写查询。
cursor, err := contactsCollection.Aggregate(ctx, bson.A{
bson.M{"$search": bson.M{"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
}}},
})
if err != nil {
panic(err)
}
var results []MyDocument
err = cursor.All(ctx, &results)
if err != nil {
panic(err)
}
英文:
Check out some tutorials or docs on how to use the MongoDB client in Go. You will need to use the bson package to write queries.
cursor, err := contactsCollection.Aggregate(ctx, bson.A{
bson.M{"$search": bson.M{"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
}}},
})
if err != nil {
panic(err)
}
var results []MyDocument
err = cursor.All(ctx, &results)
if err != nil {
panic(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论