user3142695
user3142695

Reputation: 17332

MongoDB: Getting document and only one object of an array

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"
        }
    ]
}

Upvotes: 1

Views: 51

Answers (1)

Owain Williams
Owain Williams

Reputation: 2617

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"
                }
        ]
}

Upvotes: 3

Related Questions