Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

MongoDB query to get array of nested string?



To get array of nested string in MongoDB, use dot notation in find(). Let us create a collection with documents −

> db.demo89.insertOne(
... { id: 101, Details: [ { Name: "Chris", Marks: 45 }, { Name: "David", Marks: 55, Subjects : ["MySQL", "MongoDB", "Java", "C"] } ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c163b79799acab037af51")
}
> db.demo89.insertOne(
... { id: 102, Details: [ { Name: "Mike", Marks: 48 }, { Name: "Bob", Marks: 98, Subjects : ["C++", "MySQL"] } ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c163c79799acab037af52")
}

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

> db.demo89.find();

This will produce the following output −

{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }
{ "_id" : ObjectId("5e2c163c79799acab037af52"), "id" : 102, "Details" : [ { "Name" : "Mike", "Marks" : 48 }, { "Name" : "Bob", "Marks" : 98, "Subjects" : [ "C++", "MySQL" ] } ] }

Following is the query to get array of nested string −

> db.demo89.find({ "Details.Subjects": "MongoDB"});

This will produce the following output −

{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }
Updated on: 2020-03-30T09:02:09+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements