Home » MongoDB

Using $or with a field in MongoDB

In this article, we are going to learn about the $or with a field to revaluate the data.
Submitted by Manu Jemini, on March 10, 2018

When we work on $or in MongoDB means either 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({company_name:"nissan", $or: [{type:"sedan"},
    {qty:{ $eq: 10}}] }).toArray(function(err,res){ })

After doing these things we need to console the output basically the result of code and error if any.

Then there is one last work to do is to close the connection that we made at the beginning, by simply calling the method close().

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({company_name:"nissan", $or: [{type:"sedan"}, {qty:{ $eq: 10}}] }).toArray(function(err,res){
		else if(res.length)
			console.log('No cars found');

Output in console:

Using $or with a field in MongoDB 1

Output in shell:

Using $or with a field in MongoDB 1

Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

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