Home > Net >  MongoDB query for documents with nested objects and array
MongoDB query for documents with nested objects and array

Time:08-03

I am having trouble with mongodb querying my object document. I have the following document:

{ 
"_id" : ObjectId("1"), 
"name" : "Bob", 
"fields" : {
    "DATE" : [
        {
            "fromDate" : null, 
            "values" : [
                "2022-08-01"
            ]
        }
    ]
},    
{ 
"_id" : ObjectId("2"), 
"name" : "John", 
"fields" : {
    "DATE" : [
        {
            "fromDate" : null, 
            "values" : [
                "1901-08-01"
            ]
        }
    ]
}

I am trying to get the document where fields.date[0].values is equal to 2022-08-01.

How can I achieve that? Thank you.

CodePudding user response:

You are looking for a nested element value which having some specific value/date. Since your document is incomplete so, I am creating one for illustrating the solution.

db.employees.insertMany([{ 
"name" : "Bob", 
"fields" : {
    "DATE" : [
        {
            "fromDate" : null, 
            "values" : [
                "2022-08-01"
            ]
        }
    ]
}},
{ 
"name" : "John", 
"fields" : {
    "DATE" : [
        {
            "fromDate" : null, 
            "values" : [
                "1901-08-01"
            ]
        }
    ]
}
},
{ 
"name" : "Eve", 
"fields" : {
    "DATE" : [
        {
            "fromDate" : null, 
            "values" : [
                "2022-08-01"
            ]
        }
    ]
}},
]);

Now we can find the specific value (2022-08-01 as per your requirement) from the nested array/element inside the document. Since the value resides inside "DATE" which is inside the "fields". So we can get that value easily by calling "fields.DATE". For example you can write some code like this :

db.employees.find({"fields.DATE":{"$elemMatch": {"values": "2022-08-01"}}})

From the above code you will get a result like this.

{ "_id" : ObjectId("62e94392389644cb3fc9c81f"), "name" : "Bob", "fields" : { "DATE" : [ { "fromDate" : null, "values" : [ "2022-08-01" ] } ] } }
{ "_id" : ObjectId("62e94392389644cb3fc9c821"), "name" : "Eve", "fields" : { "DATE" : [ { "fromDate" : null, "values" : [ "2022-08-01" ] } ] } }

Hope this will help you to solve this issue. Happy coding:)

  • Related