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 adjacent of a word. I am looking for most efficient method.
I will suggest using two indexes.
suppose your collection name is words
db.words.ensureIndex({word: 1}) // for next word queries
db.words.ensureIndex({word: -1}) // for previous word queries
//next word query
db.words.find({word: {$gt:"a"}}).sort({word: 1}).hint({word: 1}).limit(1)
//previous word query
db.words.find({word: {$lt:"b"}}).sort({word: -1}).hint({word: -1}).limit(1)
I hope it helps