Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get at least one match in list querying with MongoDB?
Use $in operator to get at least one match. Let us first create a collection with documents −
> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["MySQL","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2db5db64f4b851c3a13ce")
}
> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Java","C","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2db71b64f4b851c3a13cf")
}
> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Python","C++","SQL Server"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2db87b64f4b851c3a13d0")
}
>db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Ruby","Javascript","C#","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2dba9b64f4b851c3a13d1")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.atleastOneMatchDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2db5db64f4b851c3a13ce"),
"StudentFavouriteSubject" : [
"MySQL",
"MongoDB"
]
}
{
"_id" : ObjectId("5cd2db71b64f4b851c3a13cf"),
"StudentFavouriteSubject" : [
"Java",
"C",
"MongoDB"
]
}
{
"_id" : ObjectId("5cd2db87b64f4b851c3a13d0"),
"StudentFavouriteSubject" : [
"Python",
"C++",
"SQL Server"
]
}
{
"_id" : ObjectId("5cd2dba9b64f4b851c3a13d1"),
"StudentFavouriteSubject" : [
"Ruby",
"Javascript",
"C#",
"MySQL"
]
}
Following is the query to get at least one match −
>db.atleastOneMatchDemo.find({"StudentFavouriteSubject":{"$in":["MongoDB","MySQL"]}}).pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2db5db64f4b851c3a13ce"),
"StudentFavouriteSubject" : [
"MySQL",
"MongoDB"
]
}
{
"_id" : ObjectId("5cd2db71b64f4b851c3a13cf"),
"StudentFavouriteSubject" : [
"Java",
"C",
"MongoDB"
]
}
{
"_id" : ObjectId("5cd2dba9b64f4b851c3a13d1"),
"StudentFavouriteSubject" : [
"Ruby",
"Javascript",
"C#",
"MySQL"
]
}Advertisements