Take the 2-minute tour ×
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. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

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." docs.mongodb.org/manual/core/indexes –  PHPst Apr 1 '13 at 12:30
1  
Did you actually try my comment ? –  Anass Apr 1 '13 at 14:37
add comment

Your Answer

 
discard

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.