Home » MongoDB

Using $or with find in MongoDB

In this article, we are going to learn about the $or method and process to use it.
Submitted by Manu Jemini, on March 10, 2018

Here, $or in MongoDB means equal to this or that, to find a document in MongoDB through an Express server we need to full fill certain requirements:

Read more in previous article: How to use $gt in MongoDB?

In the example below, we have to search for the matching company name and quantity in this collection by using the function find;

    collection.find({ $or: [{company_name:"honda"}, {qty:{ $eq: 10}}] })
    .toArray(function(err,res){ })

Now this function will search every document with the matching field of company name as honda or quantity 10.

Just like before we have to check for the error, if any. So to check if there is any error we use simple if-else statements.

The Object error will be passed by mongo itself and it will be false or null if there is no error, otherwise we will get an error object.

If we found an error we will console.log it, otherwise we will log the result of the query.

To make an optimum server to work smooth we should always close the connection after our use of it. There the last thing we do is close the db.


JS file:

// require mongodb
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
//create url
var url = "mongodb://localhost:27017/vehicle";
//connect with mongo client
MongoClient.connect(url, function(err,db){
		//console.log tthe connected url
		console.log('Connected to ',url);

		//get refernce of using collection
		var collection = db.collection('cars');

		// to find the documents

		collection.find({ $or: [{company_name:"honda"}, {qty:{ $eq: 10}}] }).toArray(function(err,res){
			else if(res.length)
				console.log('No cars found');

Output in console:

Using $or with find in MongoDB 1

Output in shell:

Using $or with find in MongoDB 2

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

© https://www.includehelp.com (2015-2018), Some rights reserved.

close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.