skip to Main Content

The data model is something like this:

"_id":...
"special_offers": [ 0 => Object, 1 => Object, ...]

I just need to get 0 => Object, I mean, the first item of the special_offers array.

Here is what I’ve tried:

enter image description here

But as you can see, all items of the array are visible in the result. Any idea how can I get that?

2

Answers


  1. If you know the _id value of the first element then you can do:

    db.collection.find({
       special_offers: {
          $elemMatch: {
             _id: ObjectId('6349770ba47302dd542518fa')
          }
       }
    },{ 'special_offers.$':1 }
    );
    

    Or if you only know the _id of the parent document then you can do:

    db.collection.find({_id: ObjectId('650ecb0f507561a33ce927aa')},
    { 
       special_offers: {
          $first: "$special_offers"
       }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search