How can I implement MongoDB autocomplete in Golang using mongo driver?

huangapple go评论107阅读模式
英文:

How can I implement MongoDB autocomplete in Golang using mongo driver?

问题

我正在尝试在Golang中实现一个自动完成搜索,但是我在语法上一直遇到错误。

  1. contactsCollection := c.DB.Database("XYZ").Collection("contacts")
  2. result, err := contactsCollection.Aggregate([]bson.M{
  3. {
  4. "$search": bson.M{
  5. "autocomplete": bson.M{
  6. "query": searchQuery,
  7. "path": "email",
  8. "tokenOrder": "any",
  9. },
  10. },
  11. },
  12. })

searchQuery是输入的内容,email是我想要进行自动完成的字段。我假设我可以返回result

我在这里漏掉了什么?

英文:

I am trying to implement a autocomplete search in golang but I keep getting an error with the syntax

  1. contactsCollection := c.DB.Database("XYZ").Collection("contacts")
  2. result, err := contactsCollection.aggregate([{
  3. "$search": {
  4. "autocomplete": {
  5. "query": searchQuery,
  6. "path": "email",
  7. "tokenOrder": "any"
  8. }
  9. }
  10. }
  11. ])

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包来编写查询。

  1. cursor, err := contactsCollection.Aggregate(ctx, bson.A{
  2. bson.M{"$search": bson.M{"autocomplete": bson.M{
  3. "query": searchQuery,
  4. "path": "email",
  5. "tokenOrder": "any",
  6. }}},
  7. })
  8. if err != nil {
  9. panic(err)
  10. }
  11. var results []MyDocument
  12. err = cursor.All(ctx, &results)
  13. if err != nil {
  14. panic(err)
  15. }
英文:

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.

  1. cursor, err := contactsCollection.Aggregate(ctx, bson.A{
  2. bson.M{"$search": bson.M{"autocomplete": bson.M{
  3. "query": searchQuery,
  4. "path": "email",
  5. "tokenOrder": "any",
  6. }}},
  7. })
  8. if err != nil {
  9. panic(err)
  10. }
  11. var results []MyDocument
  12. err = cursor.All(ctx, &results)
  13. if err != nil {
  14. panic(err)
  15. }

huangapple
  • 本文由 发表于 2021年7月6日 04:42:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/68261919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定