1

im having trouble with mongodb querying my object document:

[
{
    "_id": "5a2ca2227c42ad67682731d4",
    "name": "name",
    "photos": [
        {
            "_id": "5a2ca22b7c42ad67682731d5",  
            "approved": false,
            "text":"good"
        },
        {
            "_id": "5a2ca72b0a1aa173aaae07da",
            "approved": true,
            "text":"bad"
        }
    ]
},
{
        "_id": "4v2ca2227cad676821731d4",
        "name": "name"
}
]

im trying to query all documents.. in this documents, the documents somethings will have photos, if exists , would like to bring the photos that have attribute approved equals to true.. but i have to bring all documents, thoses who have photos, and those who not.. im trying to use aggregation, project, unwind, but im not got any good result yet :( i need the results be like :

[
    {
        "_id": "5a2ca2227c42ad67682731d4",
        "name": "name",
        "photos": [
            {
                "_id": "5a2ca22b7c42ad67682731d5",  
                "approved": false,
                "text":"good"
            }
        ]
    },
    {
            "_id": "4v2ca2227cad676821731d4",
            "name": "name"
    }
    ]

thank you!

  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – s7vr Jan 20 '18 at 06:48

1 Answers1

1

You might need to $unwind all including the non existing photos array for getting the results

db.ph.aggregate(
    [   
        {
          $unwind:
            {
              path: "$photos",            
              preserveNullAndEmptyArrays: true
            }
        },
        {
            $match : {"photos.approved" : {$ne : true} }
        }
    ]
)

result

{
    "_id" : "5a2ca2227c42ad67682731d4",
    "name" : "name",
    "photos" : {
        "_id" : "5a2ca22b7c42ad67682731d5",
        "approved" : false,
        "text" : "good"
    }
}
{ "_id" : "4v2ca2227cad676821731d4", "name" : "name" }
> 
Saravana
  • 12,647
  • 2
  • 39
  • 57