Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 28 Apr, 2021

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:

  • 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.

Database:GFG
Collection:gfg2

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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :