S
S
Stanislav2018-07-14 00:00:13
MongoDB
Stanislav, 2018-07-14 00:00:13

How to specify only certain fields in $project when combining data using $lookup?

Hello.
There are two collections, when fetching with aggregate, I join the collection with the user by ID
Like this:

return Posts
        .aggregate([
            { $match: request.query },
            { $sort: request.sort },
            { $skip: request.skip },
            { $limit: request.limit },
            {
                $lookup: {
                    from: 'users',
                    localField: 'owner',
                    foreignField: '_id',
                    as: 'owner'
                }
            }
        ])

Naturally, the owner field contains an array with an object of all fields of the user's document, and I only need 2 fields (_id and username) I write the
following
return Posts
        .aggregate([
            { $match: request.query },
            { $sort: request.sort },
            { $skip: request.skip },
            { $limit: request.limit },
            {
                $lookup: {
                    from: 'users',
                    localField: 'owner',
                    foreignField: '_id',
                    as: 'owner'
                }
            }, {
                $project: {
                    _id: 1,
                    name: 1,
                    items: 1,
                    premiumAt: 1,
                    owner: {
                        _id: { $arrayElemAt: [ '$owner._id', 0 ] },
                        username: { $arrayElemAt: [ '$owner.username', 0 ] }
                    },
                    photos: { $arrayElemAt: [ '$photos', 0 ] },
                    comments: { $size: '$comments' }

                }
            }
        ])

As a result, I get an owner array with two fields, but I need to get rid of the array and leave only the object. I understand that you can run all this through $group, but is it possible to do without $group in this case?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question