Reputation: 18010
In a mongo collection I have a list of words (millions words).
{word:'a'}
{word:'b'}
{word:'x'}
{word:'y'}
{word:'z'}
I need to get lexical adjacents of a word (next and previous). I am looking for most efficient method.
Upvotes: 1
Views: 172
Reputation: 1724
Why don't you simply execute two queries?
The first one would look for documents with 'word > "YOURWORD"', sorting by 'word' (asc) with limit 1, then the second one would look for documents with 'word < "YOUTWORD"', sorting by 'word' (desc), again with limit 1.
I guess you've an index on the field, so it should be quite performant.
Here's a code example:
var prev = db.words.find({"word": {$gt: "YOURWORD"}}).sort({"word": 1}).limit(1);
var next = db.words.find({"word": {$lt: "YOURWORD"}}).sort({"word": -1}).limit(1);
Upvotes: 2