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.

4
  • 3
    possible duplicate of using $slice operator to get last element of array in mongodb Commented Jun 30, 2015 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? Commented Jun 30, 2015 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 Commented Jun 30, 2015 at 12:08
  • I realized that my mongodb was 2.6 and $slice is a 3+ feature. Updated, everything works. Commented Jun 30, 2015 at 16:12

2 Answers 2

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; } );
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.