swiftmongodbmongokitten

MongoKitten : Sorting by a generated field


I am trying to create the following mongo statement in MongoKitten which is a swift framework.

db.pages.find( {$and: [{$text: {$search: "ebay"}} , {"lang" : "en"} ] }, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})

In swift I have the following however I cant get it to sort by the generated field Score

let query: Query = [
            "$text": ["$search": "ebay" ],
            "lang" : ["$eq": "en"],
        ]

let projection: Projection = [
             "_id": .excluded,
            "url": "url",
            "$score": ["$meta" : "textScore"]
        ]

let sort : Sort = [
            "score": .descending
        ]

        let matchingEntities: CollectionSlice<Document> = try pages.find(query, sortedBy: sort, projecting: projection)

Anyone done anything like this?


Solution

  • Try using a custom SortOrder

    let query: Query = [
                "$text": ["$search": "ebay" ],
                "lang" : ["$eq": "en"]
    ]
    let projection: Projection = [
                "_id": .excluded,
                "url": "url",
                "score": ["$meta" : "textScore"]
    ]
    let sort : Sort = [
                "score": .custom(["$meta" : "textScore"])
    ]
    let matchingEntities: CollectionSlice<Document> = try pages.find(query, sortedBy: sort, projecting: projection)