MongoDB: Getting document and only one object of an array

Refresh

December 2018

Views

39 time

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 answers

3

Вы можете использовать $ ломтик проекцию , чтобы ограничить количество элементов массива , возвращенных. Например:

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

Вернусь:

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