英文:
mongo-driver: Unknown operator: $meta
问题
我想写这个查询 db.station.find({$and:[ {available:true}, { $text: {$search: "Romania SunFolk Radio"}}]}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
我写了以下代码:
filter := bson.D{
{"$and", bson.A{
bson.M{"available": true},
bson.M{"$text": bson.M{
"$search": query,
}},
}},
{"score", bson.M{"$meta": "textScore"}},
}
opts := options.Find()
opts.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
opts.SetLimit(1)
cursor, err := s.collection.Find(ctx, filter, opts)
if err != nil {
log.Println(err)
}
但是这段代码返回错误 (BadValue) unknown operator: $meta.
如何正确编写这个查询?
英文:
I want to write this query db.station.find({$and:[ {available:true}, { $text: {$search: "Romania SunFolk Radio"}}]}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
I wrote
filter := bson.D{
{"$and", bson.A{
bson.M{"available": true},
bson.M{"$text": bson.M{
"$search": query,
}},
}},
{"score", bson.M{"$meta": "textScore"}},
}
opts := options.Find()
opts.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
opts.SetLimit(1)
cursor, err := s.collection.Find(ctx, filter, opts)
if err != nil {
log.Println(err)
}
But this code return error (BadValue) unknown operator: $meta.
How to write this query correctly?
答案1
得分: 2
$meta
运算符是一个投影运算符,而不是过滤运算符(参见文档)。你把它传递给了过滤器。这个实际上是你问题的答案,正如评论中已经指出的那样。如果你只需要根据textScore进行排序,可以这样做。
filter := bson.D{
{"$and", bson.A{
bson.M{"available": true},
bson.M{"$text": bson.M{
"$search": query,
}},
}},
}
opts := options.Find()
opts.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
opts.SetLimit(1)
cursor, err := s.collection.Find(ctx, filter, opts)
if err != nil {
log.Println(err)
}
英文:
The $meta
operator is a projection operator not a filter operator (see docs). You're passing it in to the filter. This actually is the answer to your question as already pointed out in the comments. If all you need is to sort based on the textScore, you can do it like this.
filter := bson.D{
{"$and", bson.A{
bson.M{"available": true},
bson.M{"$text": bson.M{
"$search": query,
}},
}},
}
opts := options.Find()
opts.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
opts.SetLimit(1)
cursor, err := s.collection.Find(ctx, filter, opts)
if err != nil {
log.Println(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论