Mongodb $ project layout gets the value of the field element field of the array

Document

{
    "_id" : ObjectId("560dcd15491a065d6ab1085c"),
    "title" : "example title",
    "views" : 1,
    "messages" : [
        {
            "authorId" : ObjectId("560c24b853b558856ef193a3"),
            "authorName" : "Karl Morrison",
            "created" : ISODate("2015-10-02T00:17:25.119Z"),
            "message" : "example message"
        }
    ]
}

Project:

$project: {
    _id: 1,
    title: 1,
    views: 1,
    updated: '$messages[$messages.length-1].created' // <--- ReferenceError: $messages is not defined
}

I am trying to get the last created items from an array inside a document. I read the documentation , but this specific task did not materialize.

I found out that this is due to dot notation . However, it is not indicated how to get the last item.

+4
source share
1 answer

.find() , . .

, .aggregate(), $slice :

db.collection.find({},{ "messages": { "$slice": -1 } })

, .

( ) MongoDB - $unwind "" , $last :

db.collection.aggregate([
    { "$unwind": "$messages" },
    { "$group": {
        "_id": "$_id",
        "title": { "$last": "$title" },
        "views": { "$last": "$views" },
        "created": { "$last": "$messages.created" }
   }}
])

$slice $arrayElemAt, . $let :

    [
        { "$project": {
            "name": 1,
            "views": 1,
            "created": {
                "$let": {
                    "vars": {
                        "message": { 
                            "$arrayElemAt": [
                                { "$slice": [ "$messages", -1 ] },
                                0
                            ]
                        }
                    },
                    "in": "$$message.created"
                }
            }
        }}
    ]
+4

Source: https://habr.com/ru/post/1609867/


All Articles