How to write a function to get rows from database by multiple columns conditionally ?
MongoDB, the most popular NoSQL database, we can get rows from the database by multiple columns conditionally from MongoDB Collection using the MongoDB collection.find() function with the help of $or or $and operators. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB.
Parameters: This method takes two parameters that are not required by default:
- query: Selection query that is used to fetch the data from the database with the help of selection operators.
- projection: Projection is used to specify which field of the collection returns or not.
Return Type: The return type of this function is a JSON object.
$or or $and operators are used to apply mutliple condition on the collection.
Installing Module: You can install the mongodb module using the following command:
node install mongodb
Project Structure: The project structure will look like the following.
Running the server on Local IP: In the following command, data is the folder name.
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB Database: Our database name and collection is shown below with some dummy data.
Run index.js file using below command: