0

I've the following entity persisted on mongo in a users collection:

{
    "fullname": "Luke Tomson",
    "nicknames": [
        {
            "name": "lukeone",
            "created": ISODate("2011-05-18T19:42:56.411Z")
        },
        {
            "name": "magicluke",
            "created": ISODate("2012-01-12T19: 42: 56.411Z")
        },
        {
            "name": "superluke",
            "created": ISODate("2012-03-27T19: 42: 56.411Z")
        }
    }
]
}

How do I get the last nickname name for a user whose fullname is "Luke Tomson" ? And more specifically, how do I retrieve in the mongo shell a specific index (the first or the last) of a sorted array that was sorted upon a specific field (in this case, created).

Thanks

1 Answer 1

1

From the documentation, the second object passed to a .find is a selection of what portions of the object you want returned.

So, what you want is basically:

db.users.find({"fullname": "Luke Tomson"}, {"nicknames": { $slice: -1 } });

Though you might also want to return the _id if there are multiple "Luke Tomson"s in your DB and you need to uniquely identify them.

Sign up to request clarification or add additional context in comments.

3 Comments

And is there a way to actually retrieve the user who's last nickname is "superluke" ?
If you query an array element with a non-array value, it will return all records where at least one of the records contains the specified value. If you really need only the records where superluke is the last nickname, then you can fall back to the $where table-scan-style query. The string you pass to $where should be a single Javascript statement that evaluates to a boolean and this is a single MongoDB record. db.users.find({$where: "this.nicknames[this.nicknames.length-1].name == 'superluke'"}). You may be able to chain finds to reduce the scan size.
Oh, by the way, this page is your friend. It's very dense, but I got everything I know about MongoDB from either this page or the other I linked to you. (And experience playing with the node-mongodb-native library.)

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.