Search an array of hashes in MongoDB?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 23-May-2019 12:48:45
Advertisements