Open In App

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. 

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.



Syntax:

db.collection.find(query,projection)

Parameters: This method takes two parameters that are not required by default:



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 127.0.0.1

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

Database:GFG
Collection:gfg2

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
    collection.find({$or:[{"name":"GFG"},{"marks":"10"}]}).toArray().then((ans)=>{
        console.log(ans);
    });
     
}).catch((err) => {
  // Printing the error message
  console.log(err.Message);
})

 
Run index.js file using below command:

node index.js

Output:

 

Article Tags :