6

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.

2 Answers 2

7

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

Comments

0

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.

1 Comment

This returns only the first record and not all records with "{isPrivate: false}"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.