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!

1

1 Answer 1

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" }
> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.