- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Matching an array field that contains any combination of the provided array in MongoDB?
Use $nin operator along with $elemMatch and $not for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.combinationOfArrayDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentFavouriteTechnicalSubject":["C","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77cc8d10a061296a3c58") } > db.combinationOfArrayDemo.insertOne({"StudentName":"Mike","StudentAge":23,"StudentFavouriteTechnicalSubject":["C++","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77dc8d10a061296a3c59") } > db.combinationOfArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentFavouriteTechnicalSubject":["Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77f48d10a061296a3c5a") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.combinationOfArrayDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c7f77cc8d10a061296a3c58"), "StudentName" : "Larry", "StudentAge" : 21, "StudentFavouriteTechnicalSubject" : [ "C", "Java" ] } { "_id" : ObjectId("5c7f77dc8d10a061296a3c59"), "StudentName" : "Mike", "StudentAge" : 23, "StudentFavouriteTechnicalSubject" : [ "C++", "Java" ] } { "_id" : ObjectId("5c7f77f48d10a061296a3c5a"), "StudentName" : "David", "StudentAge" : 22, "StudentFavouriteTechnicalSubject" : [ "Java" ] }
Here is the query for matching an array field that contains any combination of the provided array in MongoDB −
> db.combinationOfArrayDemo.find({StudentFavouriteTechnicalSubject: {$not: {$elemMatch: {$nin: ['C++', 'Java']}}}}).pretty();
The following is the output −
{ "_id" : ObjectId("5c7f77dc8d10a061296a3c59"), "StudentName" : "Mike", "StudentAge" : 23, "StudentFavouriteTechnicalSubject" : [ "C++", "Java" ] } { "_id" : ObjectId("5c7f77f48d10a061296a3c5a"), "StudentName" : "David", "StudentAge" : 22, "StudentFavouriteTechnicalSubject" : [ "Java" ] }
Advertisements
To Continue Learning Please Login
Login with Google