1

I got multiple documents like this:

{
    "_id" : "sgG6G9XTvvjj7uxwQ",
    "title" : "A title",
    "notes" : [
        {
            "id" : "ePce6fBAHx9KeKjuM",
            "timestamp" : 1453731403807,
            "message" : "some text",
            "name" : "Tom"
        },
        {
            "id" : "BAHx9KeKjuMePce6f",
            "timestamp" : 1453731403808,
            "message" : "some text",
            "name" : "Bob"
        },
        {
            "id" : "ePce6fBAHx9KeKjuM",
            "timestamp" : 1453731403809,
            "message" : "some text",
            "name" : "Tom"
        }
    ]
}

I get this document by using this find-query:

Collection.find({}, { sort: { title: 1 }});

But I don't need the complete notes field. I'm only interested in the id of the last note-object. That means I have to order all notes object by timestamp and just take the first (=newest) one.

I'm not quite sure, if I can do that by the find-query or if I have to do that after getting the complete data.

So the best result for me would be:

{
    "_id" : "sgG6G9XTvvjj7uxwQ",
    "title" : "A title",
    "notes" : [
        {
            "id" : "ePce6fBAHx9KeKjuM"
        }
    ]
}

1 Answer 1

3

You can use the $slice projection to limit the number of array elements returned. For example:

db.collection.find({}, {title: 1, "notes.id": 1, notes: {$slice: 1}}).sort({title: 1});

Will return:

{
        "_id" : "sgG6G9XTvvjj7uxwQ",
        "title" : "A title",
        "notes" : [
                {
                        "id" : "ePce6fBAHx9KeKjuM"
                }
        ]
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's quite nice. Think I have to keep the timestamp and order also for timestamp. How would I do a map reduce on client?
There's a good explanation of Map-Reduce on the MongoDB Docs website docs.mongodb.org/manual/core/map-reduce
I have found a better way to do it with the $slice projection. I have updated my answer. I think this correctly solves your issue. Thanks for accepting my answer ;-)
If you need other items included in the output, just add them to the projection, e.g. "notes.message": 1, you can also just exclude the items you don't want, e.g. Collection.find({},{"notes.message": -1}) will return everything except the message in each element of the notes array. You can read more about this in the db.collection.find() reference in the MongoDB Docs: docs.mongodb.org/manual/reference/method/db.collection.find

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.