6

I am working on a nodejs/express app with Mongodb on the backend. In one of my API calls, depending on the presence of a particular querystring parameter or the other I want to issue a query to Mongodb with either a $gt or a $lt.

In some cases we want to ask for everything less than the tokenId using $lt, but in other cases we want everything greater than the tokenId using $gt. How do we do that without duplicating the queries?

Here's an example query:

collection.find({'film_id': {$in : genre}, '_id': {$lt: tokenId}}).sort({'_id': -1}).limit(25).toArray(function(error, films)

Is there a way to dynamically create the query without actually doing 2 different queries?

2 Answers 2

17

Build up your query object programmatically:

var query = {'film_id': {$in : genre}};
if (param) {
    query._id = {$lt: tokenId};
} else {
    query._id = {$gt: tokenId};
}
collection.find(query).sort({'_id': -1}).limit(25).toArray(function(error, films);

Update

Now that Node.js 4+ supports computed property names, you can create query in one step as:

var query = {
    film_id: {$in: genre},
    _id: {[param ? '$lt' : '$gt']: tokenId}
};
Sign up to request clarification or add additional context in comments.

Comments

0

The Above code may not work. The above dynamic query will be resolved to following Ex. Token is an integer 35.

collection.find("_id":"{$gt: 35}")
          .sort({'_id': -1}).limit(25).toArray(function(error, films); 

resulting in Error

The correct syntax should be:

collection.find("_id":{$gt: 35}).  

The double "" quotes should not be there.

1 Comment

Welcome to SO. Your post should be a comment or possibly an edit, not an answer. Or if you are still stuck, please post a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.