HVT7
HVT7

Reputation: 719

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.

Upvotes: 6

Views: 7653

Answers (2)

Sede
Sede

Reputation: 61273

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 }}
     ]
)

Upvotes: 7

Toan Nguyen
Toan Nguyen

Reputation: 11601

You can use $elemMatch to the result projection like this

db.collection_name.find(
{ photos:{ $elemMatch:{isPrivate: false} } },   //1

{photos:{$elemMatch:{isPrivate: false}}})  //2
  1. Find all documents that have at least a photo which is not private
  2. Select only photos that are not private for the documents found.

Upvotes: 0

Related Questions