![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
MongoDB “$and” operator for subcollection to fetch a document?
To fetch a document, use $in, instead of $and in MongoDB. Let us first create a collection with documents −
> db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Chris", ... "Subject":[ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "Name":"David", ... "Subject":[ ... "Java", ... "C" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd2271bf0181ecc422a3") } > db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Bob", ... "Subject":[ ... "C++", ... "Python" ... ] ... }, ... { ... "Name":"John", ... "Subject":[ ... "Spring", ... "Hibernate" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd4571bf0181ecc422a4") }
Display all documents from a collection with the help of find() method −
> db.demo83.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] } { "_id" : ObjectId("5e2bfd4571bf0181ecc422a4"), "Details" : [ { "Name" : "Bob", "Subject" : [ "C++", "Python" ] }, { "Name" : "John", "Subject" : [ "Spring", "Hibernate" ] } ] }
Following is the query to find a document using $in −
> db.demo83.find({ "Details" : { "$elemMatch" : {"Name" :"Chris" , "Subject":{"$in":["MongoDB"]}}}});
This will produce the following output −
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] }
Advertisements