1

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.

1
  • 1
    Do you want the entire playlist for with the videos having just the matching sub document? Please post an expected output. Commented Jan 22, 2016 at 19:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, that still comes back empty when I run it through the CLI. I'm on mongo 3.2.1
This has been fixed. $elemMatch operates on an array. My earlier solution selected a single element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.