MongoDb Accessing an array of objects with a specific property

I have one document:

{
    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 the photos that are with:

isPrivate: false

      

I am using the following query:

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

      

I've also tried:

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

      

But both return all elements in the array even those set as:

isPrivate: true

      

Please suggest.

+3


source to share


2 answers


Aggregation is the solution.

You need to deconstruct the array photos

using the operator . Then use to select documents where . you can regroup your documents on and restore the array using the operator $unwind

$match

isPrivate: false

$group

_id

photos

$push



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

      

+4


source


You can use $ elemMatch to project the result like this

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

{photos:{$elemMatch:{isPrivate: false}}})  //2

      



  • Find all documents that have at least a photo that is not private.
  • Select only those photos that are not private for the found documents.
0


source