我正在尝试使用Go Mongo驱动程序对对象中的另一个字段进行搜索自动完成。这是我的
filter := bson.A{
bson.M{
"$search": bson.M{
"compound": bson.M{
"filter": bson.M{"city": cityName},
"must": bson.M{
"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
},
},
},
},
},
}
cur, err := someCollection.Aggregate(ctx, filter)
老实说,我不太确定这是不是正确的方法。我只是想找到电子邮件地址,同时确保它们属于特定的cityName
。从其他答案中,我发现我需要使用复合,但我不确定如何使用。上面的代码导致错误"(UnknownError) Remote error from mongot :: caused by :: "filter" one of [autocomplete, compound, equals, exists, geoShape, geoWithin, near, phrase, queryString, range, regex, search, span, term, text, wildcard] must be present (from "compound")"
我该如何解决这个问题?
我最终从问题中的链接中获得了可接受的答案,并将过滤器设置为
filter := bson.A{
bson.M{
"$search": bson.M{
"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
},
},
},
bson.M{
"$match": bson.M{"city": cityName},
},
bson.M{
"$limit": 5,
},
}
它工作,但我最初的化合物尝试应该是高性能的(至少这是另一个答案在链接中说)
在复合管道中,为了提高查询性能,将多个条件合并到一个查询中,单个操作符可以有多个条件,因为它是数组格式(bson.A
)所需要的,而这是管道中操作符所缺少的。
filter := bson.A{
bson.M{
"$search": bson.M{
"compound": bson.M{
"must": bson.A{
bson.M{
"autocomplete": bson.M{
"query": searchQuery,
"path": "email",
"tokenOrder": "any",
},
},
},
"filter": bson.A{
bson.M{
"text": bson.M{
"query": cityName,
"path": "city",
},
}
},
},
},
},
}
cur, err := someCollection.Aggregate(ctx, filter)