I have a database of documents that all contain a numerical field X. I am attempting to write a query that returns a specified number of documents whose X fields are closest to a given value Y.
e.g.
List of X documents is [1, 4, 9, 2, 5, 4, 6, 8, 9, 10, 23, 2]
Y is 5, specified number of results to return is 6
would return [4, 4, 5, 6, 8, 9]
My initial thought is to get all of the documents, sort the result set by X, and trim the excess entries around Y. I'm not sure how to implement this "trimming" functionality in Mongo, however.
How can I go about crafting a query using the Java driver that does this?