Search code examples
mongodbgomongodb-querymgo

MGO : Can't canonicalize query: BadValue unknown operator: $meta


I am using the MGO to communicate with mongodb. I want to search in a collection, and to sort the results by search score.

collection.Find(bson.M{
    "$text": bson.M{"$search": "mysearch"},
    "score": bson.M{"$meta": "textScore"},
})

But I get this error :

Can't canonicalize query: BadValue unknown operator: $meta (status code : 500)

When I only try with $text, it works.

I use the same bson structure than here : MongoDB - Can't canonicalize query: BadValue unknown operator: $meta

Thanks


Solution

  • The problem here is that you are using a BSON "map" as the argument with the "projection" as part of the "query". Instead use the .Select() method in chaining for projection:

    collection.Find(
        bson.M{ "$text": bson.M{ "$search": "mysearch" } }
    ).Select( 
        bson.M{ "score": bson.M{ "$meta": "textScore" } }
    )
    

    Just like in the standard API examples, the "query" and "projection" portions are "separated" from each other.