2

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.

Mia
  • 6,220
  • 12
  • 47
  • 81
  • 3
    possible duplicate of [using $slice operator to get last element of array in mongodb](http://stackoverflow.com/questions/21952005/using-slice-operator-to-get-last-element-of-array-in-mongodb) – scx Jun 30 '15 at 11:47
  • 1
    Did you try using `$slice` this way `db.test.find({},{"images.size": 0, "images": {"$slice": -1} })` or get the url value using `findOne()` as `db.test.findOne({},{"images.size": 0, images: {$slice: -1} }).images[0].url`? – chridam Jun 30 '15 at 11:47
  • I am not sure what is gonig wrong there but $slice: -1 does not make any difference at all, it looks like I am doing a .find() rather than sending a proper query @chridam – Mia Jun 30 '15 at 12:08
  • I realized that my mongodb was 2.6 and $slice is a 3+ feature. Updated, everything works. – Mia Jun 30 '15 at 16:12

2 Answers2

1

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; } );
1

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.

Mia
  • 6,220
  • 12
  • 47
  • 81