3

I'm trying to do an mongodb aggregation with first doing a lookup and after that projecting the correct fields to remove unnecessary fields that I don't have to use.

For example if I have 2 collections.

Users collection:

user
{
    id: int
    username: string
    password: string
}

User_data collection:

user_data
{
    id: int
    user_id: int
    name: string
    email: string
}

My aggregation code:

findQuery = [
    {
        '$lookup':
        {
            from: 'user_data',
            localField: 'id',
            foreignField: 'user_id',
            as: 'user_data'
        }
    },
    {
        '$project':
        {
            "id": 1,
            "username": 1,
            "user_data": 1
        }
    }];

Wished output:

{
    _id: "<random>",
    id: 1,
    username: user1,
    user_data: [
        {
            _id: "<random>",
            user_id: 1,
            name: "ABC"
        },
        {
            _id: "<random>",
            user_id: 1,
            name: "DEF"
        }
    ]
},
{
    _id: "<random>",
    id: 2,
    username: user2,
    user_data: [
        {
            _id: "<random>",
            user_id: 2,
            name: "GHI"
        },
        {
            _id: "<random>",
            user_id: 2,
            name: "JKL"
        }
    ]
}

My output:

{
    _id: "<random>",
    id: 1,
    username: user1,
    user_data: [
        {
            _id: "<random>",
            id: 1,
            user_id: 1,
            name: "ABC",
            email: "abc@abc.com"
        },
        {
            _id: "<random>",
            id: 2,
            user_id: 1,
            name: "DEF",
            email: "def@abc.com"
        }
    ]
},
{
    _id: "<random>",
    id: 2,
    username: user2,
    user_data: [
        {
            _id: "<random>",
            id: 3,
            user_id: 2,
            name: "GHI",
            email: "GHI@abc.com"
        },
        {
            _id: "<random>",
            id: 4,
            user_id: 2,
            name: "JKL",
            email: "jkl@abc.com"
        }
    ]
}

How do I fix this? I tried already to put $project inside the $project. But that didn't work for me.

BJNM
  • 63
  • 6

0 Answers0