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
MongoDB query to test if a value is in array?
To check for a specific value, use $in. Let us first create a collection with documents −
> db.testInArray.insertOne({"ListOfNumbers":[10,56,78,90,32]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04d42df5e889d7a519950d")
}
> db.testInArray.insertOne({"ListOfNumbers":[56,78,91,100]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04d588f5e889d7a519950e")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.testInArray.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e04d42df5e889d7a519950d"),
"ListOfNumbers" : [
10,
56,
78,
90,
32
]
}
{
"_id" : ObjectId("5e04d588f5e889d7a519950e"),
"ListOfNumbers" : [
56,
78,
91,
100
]
}
Here is the query to test if a value is in array −
> db.testInArray.find({ ListOfNumbers:{ "$in" : [90]} });
This will produce the following output −
{ "_id" : ObjectId("5e04d42df5e889d7a519950d"), "ListOfNumbers" : [ 10, 56, 78, 90, 32 ] }Advertisements