Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic queries in MongoDB and Node.js

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?

like image 240
Raj Avatar asked Dec 01 '12 16:12

Raj


People also ask

What is the difference between MongoDB query and nodeJS query?

There are many ways of defining the query in MongoDB. It all depends upon the requirements. All these methods and query filters we discussed are also supported in Nodejs. There is absolutely no difference. We hope that these examples of queries with NodeJS and MongoDB were of some assistance.

How to dynamically build MongoDB query?

How to dynamically build MongoDB query? To build query dynamically, you need to write some script. Let us first create a collection with documents − Display all documents from a collection with the help of find () method −

How do I use query operators in MongoDB?

In a query document, you can match fields against literal values (e.g. { title: 'The Room' }) or you can compose query operators to express more complex matching criteria. In this guide, we cover the following categories of query operators in MongoDB and show examples on how to use them:

How to use regular expressions in MongoDB query?

Run "demo_mongodb_query.js" C:\Users\ Your Name >node demo_mongodb_query.js You can write regular expressions to find exactly what you are searching for. Regular expressions can only be used to query strings.


1 Answers

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}
};
like image 55
JohnnyHK Avatar answered Sep 27 '22 21:09

JohnnyHK