
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
Find Document That Matches Same Array Elements in MongoDB
To find a document that matches the same array elements, use find() and within that, use $all. The $all operator selects the documents where the value of a field is an array that contains all the specified elements.
Let us create a collection with documents −
> db.demo543.insertOne({id:101, subject:["MySQL", "Java" ,"C","Python"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e1b2f9e5f92834d7f05c9") } > db.demo543.insertOne({id:102, subject:["MySQL", "MongoDB" ,"SQL Server"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e1b2f9e5f92834d7f05ca") }
Display all documents from a collection with the help of find() method −
> db.demo543.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e1b2f9e5f92834d7f05c9"), "id" : 101, "subject" : [ "MySQL", "Java", "C", "Python" ] } { "_id" : ObjectId("5e8e1b2f9e5f92834d7f05ca"), "id" : 102, "subject" : [ "MySQL", "MongoDB", "SQL Server" ] }
Following is the query to find a document that matches the same array elements in MongoDB −
> db.demo543.find({ ... "subject": { $all: [ "MySQL", "MongoDB", "SQL Server"], $size: 3 } ... })
This will produce the following output −
{ "_id" : ObjectId("5e8e1b2f9e5f92834d7f05ca"), "id" : 102, "subject" : [ "MySQL", "MongoDB", "SQL Server" ] }
Advertisements