user1460015
user1460015

Reputation: 2003

Retrieving a single Object inside an Array using the MongoDB Mongoose driver

I have a document that looks similar to this:

{
    'user_id':'{1231mjnD-32JIjn-3213}',
    'name':'John',
    'campaigns':
        [
            {
                'campaign_id':3221,
                'start_date':'12-01-2012',
                'worker_id': '00000'
            },
            {
                'campaign_id':3222,
                'start_date':'13-01-2012',
                'worker_id': '00000'
            },
            ...
            etc
            ...
        ]
}

I am trying to retrieve an object in the campaigns array.
For example, I would like to find the campaign_id under name: "John" given a positional element of, say, 7.
In other words, find and return the campaign_id at position 7 in the array campaigns.

Using the mongoose driver:

camps.findOne({name: 'John'}, {name: 1, "campaigns.7.campaign_id": 1}, function(err, camp) {etc});
camps.findOne({name: 'John'}, {name: 1, "campaigns[7].campaign_id": 1}, function(err, camp) {etc});

Here I am trying to retrieve "campaigns.7.campaign_id": 1 at position 7.
Unfortunately, this is does not return the specific campaign_id.

Any suggestions on how to retrieve the object at position 7 inside the array?

Upvotes: 1

Views: 473

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

Use the $slice projection operator to do this:

camps.findOne({name: 'John'}, {
    name: 1, 
    'campaigns.campaign_id': 1, 
    campaigns: {$slice: [7, 1]}
}, ...

Upvotes: 1

Related Questions