Johnny Willer
Johnny Willer

Reputation: 3917

Extract field from Object without $project twice MongoDB

Well, maybe it's a simple question but I didn't find any satisfied answer in mongoDB documentation about aggregation framework.

If I do a lookup that results in a array of matching docs, how I project only a field of the last element?

db.collection.aggregate([
    {
        $lookup: {
            .... some lookup pipeline ....,
            as: "matchedObjects"
        }
    },
    {
        // Here I get the last Object
        $project: {
            doc:  { $arrayElemAt: [ { $slice: ["$matchedObjects", -1 ] }, 0 ]}
        }
    },
    {      
        // extract what I want
        $project: {
            field:  "$doc.field"
        }
    }
])

Well, how I do this with only the first $project

Upvotes: 1

Views: 444

Answers (1)

mickl
mickl

Reputation: 49945

You can use $let to capture last element in temporary variable and then reference that variable to get field:

db.collection.aggregate([
    {
        $project: {
            field: {
                $let: {
                    vars: { doc:  { $arrayElemAt: [ { $slice: ["$matchedObjects", -1 ] }, 0 ]} },
                    in: "$$doc.field"
                }
            }
        }
    }
])

Upvotes: 1

Related Questions