
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
Use $elemMatch on First-Level Array in MongoDB
You can use $in operator instead of $elemMatch on first level array. The syntax is as follows
db.yourCollectionName.find({yourFieldName:{$in:["yourValue"]}}).pretty();
Let us first create a collection with documents
>db.firstLevelArrayDemo.insertOne({"StudentName":"Chris","StudentTechnicalSkills":["Mongo DB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2360f66324ffac2a7dc71") } >db.firstLevelArrayDemo.insertOne({"StudentName":"Robert","StudentTechnicalSkills":["C","J ava","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2362766324ffac2a7dc72") }
Following is the query to display all documents from a collection with the help of find() method
> db.firstLevelArrayDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5ca2360f66324ffac2a7dc71"), "StudentName" : "Chris", "StudentTechnicalSkills" : [ "MongoDB", "MySQL", "SQL Server" ] } { "_id" : ObjectId("5ca2362766324ffac2a7dc72"), "StudentName" : "Robert", "StudentTechnicalSkills" : [ "C", "Java", "C++" ] }
Following is the query to match on first level array
> db.firstLevelArrayDemo.find({StudentTechnicalSkills:{$in:["MongoDB"]}}).pretty();
This will produce the following output
{ "_id" : ObjectId("5ca2360f66324ffac2a7dc71"), "StudentName" : "Chris", "StudentTechnicalSkills" : [ "MongoDB", "MySQL", "SQL Server" ] }
Advertisements