Sunday, 6 June 2021

Mongo Shell: Access the properties of a document directly

Once you have a reference to the document, you can access the properties of a document using dot (.) notation.

 

Let’s experiment with employee collection.

> db.employee.find().pretty()
{
    "_id" : ObjectId("60bcd0dd8251689f64fb3eee"),
    "id" : 1,
    "firstName" : "Joel",
    "lastName" : "chelli"
}
{
    "_id" : ObjectId("60bcd0dd8251689f64fb3eef"),
    "id" : 2,
    "firstName" : "Ananad",
    "lastName" : "Bandaru"
}
{
    "_id" : ObjectId("60bcd0dd8251689f64fb3ef0"),
    "id" : 3,
    "firstName" : "Gopi",
    "lastName" : "Battu",
    "projects" : [
        {
            "projectId" : "ind_cpcs",
            "name" : "cpcs",
            "description" : "cabin pressure control system"
        },
        {
            "projectId" : "ind_veh_tracker",
            "name" : "vehicle tracker",
            "description" : "Track the vehicle"
        }
    ]
}
{
    "_id" : ObjectId("60bcd0dd8251689f64fb3ef1"),
    "id" : 4,
    "firstName" : "Ritwik",
    "lastName" : "Mohenthy",
    "hobbies" : [
        "cooking",
        "trekking",
        "listening to music"
    ]
}

 

Get the document of employee Gopi

> db.employee.findOne({"firstName" : "Gopi"})
{
    "_id" : ObjectId("60bcd0dd8251689f64fb3ef0"),
    "id" : 3,
    "firstName" : "Gopi",
    "lastName" : "Battu",
    "projects" : [
        {
            "projectId" : "ind_cpcs",
            "name" : "cpcs",
            "description" : "cabin pressure control system"
        },
        {
            "projectId" : "ind_veh_tracker",
            "name" : "vehicle tracker",
            "description" : "Track the vehicle"
        }
    ]
}

 

Print firstName property

> db.employee.findOne({"firstName" : "Gopi"}).firstName
Gopi

 

Get all the projects that Gopi is working on

> db.employee.findOne({"firstName" : "Gopi"}).projects
[
    {
        "projectId" : "ind_cpcs",
        "name" : "cpcs",
        "description" : "cabin pressure control system"
    },
    {
        "projectId" : "ind_veh_tracker",
        "name" : "vehicle tracker",
        "description" : "Track the vehicle"
    }
]

 

Get first project details from projects array

> db.employee.findOne({"firstName" : "Gopi"}).projects[0]
{
    "projectId" : "ind_cpcs",
    "name" : "cpcs",
    "description" : "cabin pressure control system"
}

 

Get the first project description

> db.employee.findOne({"firstName" : "Gopi"}).projects[0].description
cabin pressure control system

 

Note

This ‘.’ notation works only when you have reference to single document. It will not work with multiple documents.

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment