How can I 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"
   ]
}

Updated on: 30-Jul-2019

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements