ADVERTISEMENT
ADVERTISEMENT

Home » MongoDB

Purpose of $in in MongoDB

In this article, we are going to learn about $in and the purpose behind using it.
Submitted by Manu Jemini, on March 10, 2018

Using $in in MongoDB means the field equals to any value in the array, 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 type in this collection by using the function find;

    collection.find({type: { $in: ["sedan","sports"]}}).
    toArray(function(err,res){ })

Now this function will search every document with the matching field type with "sedan", "sports".

Then there are these basic things we need to do is to print the error in code if any, and the connection needs to be get closed before the code ends.

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){
	if(err)
	{
		console.log(err);
	}
	else
	{
		//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({type: { $in: ["sedan","sports"]}}).toArray(function(err,res){
			if(err)
			{
				console.log(err);
			}
				else if(res.length)
			{
				console.log(res);
			}
			else
			{
				console.log('No cars found');
			}
			db.close();
		})
	}
});

Output in console:

Purpose of $in in MongoDB 1
<

Output in shell:

Purpose of $in in MongoDB 2

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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 some rights reserved.