A
A
Alexander Mylchenko2019-04-03 11:24:09
MongoDB
Alexander Mylchenko, 2019-04-03 11:24:09

How to change the aggregate $group that returns null when $lookup is an empty array?

Good afternoon/evening,
Faced with sl. situation.
In general:
There is a collection of "recommendations", it has an entry sl. type:

{
    "_id" : ObjectId("5c995106deafcc7c86b9f284"),
    "id" : 777,
    "name" : "developers",
    "likesPeople" : [ 
        { "id" : 579 }, 
        { "id" : 398 }
    ]
}

When I do a $lookup with a collection of users by id's in the recommendations.likesPeople array (in the following way):
db.getCollection('recommendations').aggregate([
    { $match: { id: 777 }},
    { $unwind: "$likesPeople" },
    { $lookup: {
        from: "users",
        localField: "likesPeople.id",
        foreignField: "id",
        as: "likesPeople"
    } },
    { $unwind: "$likesPeople" },
    { $group : { 
            _id: '$_id',
            likesPeople: { $push: "$likesPeople"},
            id: { $first: '$id' }
        }
    }
])

I get the result:
{
    "_id" : ObjectId("5c995106deafcc7c86b9f284"),
    "id" : 777,
    "likesPeople" : [ 
        {
            "_id" : ObjectId("5c99500adeafcc7c86b9f283"),
            "id" : 579,
            "name" : "Вася"
        }, 
        {
            "_id" : ObjectId("5c99b429deafcc7c86b9f28b"),
            "id" : 398,
            "name" : "Маша"
        }
    ]
}

The problems start when the likesPeople array in the recommendations collection is empty:
{
    "_id" : ObjectId("5c995106deafcc7c86b9f284"),
    "id" : 777,
    "name" : "developers",
    "likesPeople" : []
}

After executing $lookup/$group, I get an empty result and as a result I lose the ability to get all other fields ( _id, id, name ). To some extent, this is logical ...
What is the question : What needs to be changed in the mongodb query, so that in cases where the likesPeople in the collection has no values ​​\u200b\u200b(empty), the result would return all the other fields to me:
{
    "_id" : ObjectId("5c995106deafcc7c86b9f284"),
    "id" : 777,
    "name" : "developers",
    "likesPeople" : null // или что угодно
}

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