Vin
Vin

Reputation: 31

Filter sub document array

db.doc.find({},{"sections.rows.Desk":1}) returns desks list but also empty rows i.e. where desk attribute doesn't exist in rows array...

I would like to eliminate empty results. How to go about it?

Thanks!

My document "doc" has the following format. "docs": {

    "sections" : [
        {
            "name" : "Request Details", 
            "rows" : [
                {
                    "Desk" : "IT4"
                }
            ]
        }, 
        {
            "name" : "Approval", 
            "rows" : [
                {
                    "Approval" : ""
                }
            ]
        }
    ]
}

Upvotes: 2

Views: 177

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191799

You will have to use the aggregation framework, particularly the $unwind operator to be able to query against individual array elements and get the ones you are after. Currently with the way .find works you will get the entire document if it matches your query.

db.docs.aggregate({$unwind: "$sections"}, {$match: {"sections.rows.Desk": {$exists: 1}}});

Upvotes: 1

Related Questions