In a mongo collection I have a list of words (millions words).


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

  • In your case you should use indexes with direction. Try to insert db.words.insert({word: "aa"}), and then try to look for the previous word of 'b', you will get 'a' not 'aa'.
    – Anass
    Apr 1 '13 at 12:24
  • "When creating an index, the number associated with a key specifies the direction of the index. The options are 1 (ascending) and -1 (descending). Direction doesn’t matter for single key indexes or for random access retrieval but is important if you are doing sort queries on compound indexes." docs.mongodb.org/manual/core/indexes Apr 1 '13 at 12:30
  • 1
    Did you actually try my comment ?
    – Anass
    Apr 1 '13 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.