Reputation: 6531
Here is my document structure:
{
"name": "object name",
"details": "object details",
"images": [{
"size": "large",
"url": "http://domain.com/large.png"
}, {
"size": "medium",
"url": "http://domain.com/medium.png"
}, {
"size": "small",
"url": "http://domain.com/small.png"
}]
}
Some documents only have the "large" images, some of them have all, some of them only have the "medium" image. What I want to do is, to get the url of the last element of the array.
Here is what I tried:
.find({},{"images.url":1})
Returns all url's. I tried using $slice as well, without any success (parameter errors).
Please note that I am trying to get the "url of the last element" not the "last element"
Looking for a solution.
Upvotes: 2
Views: 104
Reputation: 6531
I realized that the reason $slice was not working for me was that my mongodb was version 2.6.6 I updated my mongodb to version 3.0.4 and it works perfectly as follows:
.find({},{"images.url":1,"images.url":{$slice:-1}})
Thank you for all the comments so far.
Upvotes: 1
Reputation: 131
You can use map() to filter the response :
.find({}, { _id: 0, name: 0, details: 0, images: { $slice: -1 } }).map( function(u) { return u.images[0].url; } );
Upvotes: 1