Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Access array of objects with certain property

I have one document as follows:

{
    user: 'hvt07',
    photos: [
    {
        link: 'http://link.to.com/image1.jpg',
        isPrivate: true
    },
    {
        link: 'http://link.to.com/image2.jpg',
        isPrivate: false
    }
    ]
}

I want to get all photos which are with:

isPrivate: false

I am using the following query:

db.collection_name.find({ photos:{ $elemMatch:{isPrivate: false} } }).pretty()

I have also tried:

db.collection_name.find({'photos.isPrivate': true}).pretty()

But both return all elements in the array even ones that are set as :

isPrivate: true

Please suggest.

like image 888
HVT7 Avatar asked May 13 '15 12:05

HVT7


1 Answers

Aggregation is the solution.

You need to deconstruct the photos array using the $unwind operator. Next use the $match to select documents where isPrivate: false. The $group you can regroup your documents by _id and reconstruct your photos array using the $push operator

db.collection_name.aggregate(
     [
       {$unwind: "$photos"}, 
       {$match: {"photos.isPrivate": false}}, 
       {$group: {"_id": {"id": "$_id", "user": "$user"}, photos: {$push: "$photos"}}}
       {$project: {"_id": "$_id.id", "user": "$_id.user", "photos": 1, "_id": 0 }}
     ]
)
like image 182
styvane Avatar answered Oct 04 '22 15:10

styvane