Search array of objects in a MongoDB collection?


To search array of objects, use MongoDB find().The find() method selects documents in a collection or view and returns a cursor to the selected documents..

Let us create a collection with documents −

> db.demo484.insertOne(
... { 'id' : 1, 'details' : [ { 'Name1' : 'Chris' }, { 'Name2' : 'David' }, { 'Name3' : 'Bob' } ] }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82e3a4b0f3fa88e22790a1")
}
> db.demo484.insertOne(
... { 'id' : 1, 'details' : [ { 'Name1' : 'Chris' }, { 'Name2' : 'Carol' }, { 'Name3' : 'Bob' } ] }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82e3a4b0f3fa88e22790a2")
}
> db.demo484.insertOne(
... { 'id' : 1, 'details' : [ { 'Name1' : 'Chris' }, { 'Name2' : 'Carol' }, { 'Name3' : 'Mike' } ] }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82e3a4b0f3fa88e22790a3")
}

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

> db.demo484.find();

This will produce the following output −

{ "_id" : ObjectId("5e82e3a4b0f3fa88e22790a1"), "id" : 1, "details" : [ { "Name1" : "Chris" }, {
"Name2" : "David" }, { "Name3" : "Bob" } ] }
{ "_id" : ObjectId("5e82e3a4b0f3fa88e22790a2"), "id" : 1, "details" : [ { "Name1" : "Chris" }, {
"Name2" : "Carol" }, { "Name3" : "Bob" } ] }
{ "_id" : ObjectId("5e82e3a4b0f3fa88e22790a3"), "id" : 1, "details" : [ { "Name1" : "Chris" }, {
"Name2" : "Carol" }, { "Name3" : "Mike" } ] }

Following is the query to search array of objects in a MongoDB collection −

> db.demo484.find(
... {$or: [
...    {'details.Name2': 'Carol', 'details.Name3': 'Mike'},
...    {'details.Name2': 'Carol', 'details.Name3': 'Bob'}
... ]}
... )

This will produce the following output −

{ "_id" : ObjectId("5e82e3a4b0f3fa88e22790a2"), "id" : 1, "details" : [ { "Name1" : "Chris" }, {
"Name2" : "Carol" }, { "Name3" : "Bob" } ] }
{ "_id" : ObjectId("5e82e3a4b0f3fa88e22790a3"), "id" : 1, "details" : [ { "Name1" : "Chris" }, {
"Name2" : "Carol" }, { "Name3" : "Mike" } ] }

Updated on: 11-May-2020

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements