MongoDB query to get array of nested string?

MongoDBDatabaseBig Data Analytics

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" ] } ] }
raja
Published on 30-Mar-2020 09:01:03
Advertisements