mongo-driver: 未知操作符:$meta

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

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

huangapple
  • 本文由 发表于 2021年6月16日 22:07:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/68004332.html
匿名

发表评论

匿名网友

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

确定