How to retrieve only specific element from an array in MongoDB - Using $elemMatch operator

You are here : Home / MongoDB Tutorial


Contents of page >
  • 1) Before retrieve only specific element from an array in MongoDB
  • 2) Let’s use $elemMatch projection operator - It alters the returned document to contain  only the first matched element of array.
  • 3) SUMMARY>

How to retrieve only specific element from an array in document in MongoDB


We will use $elemMatch projection operator - It alters the returned document to contain  only the first matched element of array.


1) Before retrieve only specific element from an array in MongoDB


Let's create new collection and insert documents in it >
> db.testArr.insert( {CARS : [ { car : "BMW"}, {car : "FERRARI"} ] } )
> db.testCollection.insert({name: 'bcd'})
> db.testCollection.insert({name: 'def'})
First line above will create table (or collection) (if table already exists it will insert documents in it).


Query/Read all documents of collection >
> db.testArr.find();
{ "_id" : ObjectId("585137751317888bda93e53d"), "CARS" : [ { "car" : "BMW" }, { "car" : "FERRARI" } ] }
>
1 document was found.

2) Let’s use $elemMatch projection operator - It alters the returned document to contain only the first matched element of array.


Now, retrieve only specific element from an array in MongoDB >
> db.testArr.find( {"CARS.car": "BMW"}, {_id: 0, CARS: {$elemMatch: {car: "BMW"}}});
{ "CARS" : [ { "car" : "BMW" } ] }
>
In our case  $elemMatch helped us in retrieving only specific element i.e. BMW and skipped FERRARI.


3) SUMMARY>
So in this mongoDB tutorial we learned how to retrieve only specific element from an array in MongoDB using $elemMatch.

Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database

Update documents in collection in mongoDB

Create new database in mongoDB

Create new collection(table) in mongoDB

Data Modelling in MongoDB - Multiple tables


eEdit
Must read for you :