Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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

share|improve this answer
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." – PHPst Apr 1 '13 at 12:30
Did you actually try my comment ? – Anass Apr 1 '13 at 14:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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