Search an array of hashes in MongoDB?


Let us first create a collection with documents −

> db.searchAnArrayDemo.insertOne({_id:1,"TechnicalDetails":[{"Language":"MongoDB"}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.searchAnArrayDemo.insertOne({_id:2,"TechnicalDetails":[{"Language":"MySQL"}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.searchAnArrayDemo.insertOne({_id:3,"TechnicalDetails":[{"Language":"MongoDB"}]});
{ "acknowledged" : true, "insertedId" : 3 }
> db.searchAnArrayDemo.insertOne({_id:4,"TechnicalDetails":[{"Language":"MongoDB"}]});
{ "acknowledged" : true, "insertedId" : 4 }
> db.searchAnArrayDemo.insertOne({_id:5,"TechnicalDetails":[{"Language":"Java"}]});
{ "acknowledged" : true, "insertedId" : 5 }

Following is the query to display all documents from a collection with the help of find() method −

> db.searchAnArrayDemo.find().pretty();

This will produce the following output −

{ "_id" : 1, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] }
{ "_id" : 2, "TechnicalDetails" : [ { "Language" : "MySQL" } ] }
{ "_id" : 3, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] }
{ "_id" : 4, "TechnicalDetails" : [ { "Language" : "MongoDB" } ] }
{ "_id" : 5, "TechnicalDetails" : [ { "Language" : "Java" } ] }

Following is the query to search an array of hashes −

> db.searchAnArrayDemo.find({'TechnicalDetails.Language':'MongoDB'}).count();

This will produce the following output −

3

Updated on: 30-Jul-2019

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements