hybrid9
hybrid9

Reputation: 2646

Return single nested array object using mongoose

I've been wrestling with this all morning. I'm trying to pull a single nested object from an array. I've been following along with the mongo query docs, but I cannot return the desired object.

videocollection

{
  "_id": ObjectID("95738ax1795b45f0hgn8dbfd8"),
  "playlist": [
    {
      "videos": [
        {
          "title": "Video Title 1",
          "slug": "video-1"      
        },
        {
          "title": "Video Title 2",
          "slug": "video-2"
        }
      ],
      "related": [
        {
          ....
        }
      ]
    }
  ]
}

When I run the following queries in the MongoDB CLI I either get zero result returned or the entire document.

db.videocollection.find({}, { $elemMatch: {'playlist.videos.slug':'video-2'} } )

db.videocollection.find({}, {_id: 0, 'playlist.0.videos': {$elemMatch: {'slug': 'video-2' }}})

I'm trying to query against the slug in the videos array.

Upvotes: 1

Views: 2596

Answers (1)

gnerkus
gnerkus

Reputation: 12037

The proper query would be:

db.videocollection.find({ 'playlist.$.videos': { $elemMatch: { 'slug': 'video-2'} } })

The $ is the positional operator and represents any index in an array.

Upvotes: 1

Related Questions