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

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

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)
}

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:

确定