Querying one filed based on another field

Hi, I’m totally new to MongoDB and pretty new to NoSQL in general.

I’m working with a schema like this:

{ _id: ObjectId,
lemma: string,
alpha-index: long,
… }

The alpha-index is a unique number that sorts the documents in a particular order. What I’m trying to do is to search for a lemma (a string) and the query should find the alpha-index of that lemma (let’s call it K) and then return all the documents that have alpha-index greater than K - 25 and lesser than K + 25.

Do I need to perform two queries?
find(lemma:“myString”)
And then obtain K from this document and do:
find({alpha-index: {$gt:(K-25), $lt:(K+25)}})

Or can it be done in a single query?

Thank you!!!

Hi @Hernan_Ruiz and welcome to the community!
If I understand you correctly, you are simply asking to satisfy an equality and a range in one query?
If yes is the answer in this case, that should simply be the solution:

db.collectionName.find({lemma:"string",alpha-index: {$gt:(K-25), $lt:(K+25)}})

Regards

Hey.
Thanks for your reply.

The problem I have is that K is an integer I have to obtain in the first query. I’m currently doing:

K = the alpha-index value obtained in db.myCollection.findOne(lemma:“myString”, alpha-index:1)

And then:
db.myCollection.find({alpha-index: {$gt:(K-25), $lt:(K+25)}})

Can these two queries be condensed into one? I suppose not, because once you find the match for the first query, you need to go back to search the entire collection.

But the thing is, alpha-index is actually an indexed fiend, and on top of that, its values mimic an index (unique integers, consecutive numbers). So I don’t know if there’s a way to extract the documents between K-25 and K+25 without running an additional query on the entire collection and do something more efficient.

I don’t know if I’m being clear here.

Thanks again!!