Skip to content
Related Articles
Open in App
Not now

Related Articles

How to write a function to get rows from database by multiple columns conditionally ?

Improve Article
Save Article
  • Last Updated : 17 Aug, 2021
Improve Article
Save Article

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. 

collection.find() is the method of the MongoDB module in the node.js that is used to select the rows from the collections of a particular database present in the database of the 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 multiple 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

MongoDB Database: Our database name and collection is shown below with some dummy data.


Filename: index.js


// Requiring module
const MongoClient = require("mongodb");
// Connection URL
// Our database name
const databasename="GFG"
MongoClient.connect(url).then((client) => {
    const connect = client.db(databasename);
    // Connecting to collection
    const collection = connect.collection("gfg2"); 
    // Function call with $or operator
}).catch((err) => {
  // Printing the error message

Run index.js file using below command:

node index.js



My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!