How to filter documents based on an array in MongoDB?

MongoDBDatabaseBig Data Analytics

To filter documents based on an array, use $elemMatch. The $elemMatch operator matches documents that contain an array field.

Let us create a collection with documents −

> db.demo453.insertOne(
... { _id: 101, details: [ { Name: "David", Marks: 60 }, { Name: "Mike", Marks: 55} ] }
... )
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo453.insertOne(
... { _id: 102, details: [ { Name: "Bob", Marks: 80 }, { Name: "Sam", Marks: 78} ] }
... )
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo453.insertOne(
... { _id: 103, details: [ { Name: "Carol", Marks: 67 }, { Name: "John", Marks: 79} ] }
... )
{ "acknowledged" : true, "insertedId" : 103 }

Display all documents from a collection with the help of find() method −

> db.demo453.find();

This will produce the following output −

{ "_id" : 101, "details" : [ { "Name" : "David", "Marks" : 60 }, { "Name" : "Mike", "Marks" : 55 } ] }
{ "_id" : 102, "details" : [ { "Name" : "Bob", "Marks" : 80 }, { "Name" : "Sam", "Marks" : 78 } ] }
{ "_id" : 103, "details" : [ { "Name" : "Carol", "Marks" : 67 }, { "Name" : "John", "Marks" : 79 } ] }

Following is the query to filter documents based on an array −

> db.demo453.find(
... { details: { $elemMatch: {Marks: { $gte: 75 } } } }
... )

This will produce the following output −

{ "_id" : 102, "details" : [ { "Name" : "Bob", "Marks" : 80 }, { "Name" : "Sam", "Marks" : 78 } ] }
{ "_id" : 103, "details" : [ { "Name" : "Carol", "Marks" : 67 }, { "Name" : "John", "Marks" : 79 } ] }
raja
Published on 11-May-2020 09:11:47
Advertisements