MongoDB query to match documents that contain an array field

MongoDBDatabaseBig Data Analytics

To match documents that contain an array field, use the $elemMatch operator. Let us create a collection with documents −

> db.demo592.insertOne(
...    {
...       "id":101,
...       "details" : [
...          { "Name" : "Chris", "Value" : "200"},
...          {"Name" : "David", "Value" : "800"}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e930d8ffd2d90c177b5bcd6")
}
> db.demo592.insertOne(
... {
...    id:102,
...    "details" : [
...       { "Name" : "Chris", "Value" : "500"},
...       {"Name" : "David", "Value" : "900"}
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e930d90fd2d90c177b5bcd7")
}

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

> db.demo592.find();

This will produce the following output −

{ "_id" : ObjectId("5e930d8ffd2d90c177b5bcd6"), "id" : 101, "details" : [
   { "Name" : "Chris", "Value" : "200" },
   { "Name" : "David", "Value" : "800" }
] }
{ "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [
   { "Name" : "Chris", "Value" : "500" },
   { "Name" : "David", "Value" : "900" }
] }

Following is the query to match −

> db.demo592.find(
...    {
...       "$and" : [
...          { "details" : { "$elemMatch" : { "Name" : "Chris", "Value" : { "$gte" : "500" } } } },
...          { "details" : { "$elemMatch" : { "Name" : "David", "Value" : { "$gte" : "600" } } } }
...       ]
...    }
... );

This will produce the following output −

{ "_id" : ObjectId("5e930d90fd2d90c177b5bcd7"), "id" : 102, "details" : [
   { "Name" : "Chris", "Value" : "500" }, { "Name" : "David", "Value" : "900" } 
] }
raja
Published on 15-May-2020 10:23:26
Advertisements