MongoDB Aggregation - 查找后的项目

时间:2018-02-07 10:19:49

标签: mongodb aggregation-framework

我正在尝试通过首先进行查找来进行mongodb聚合,然后投射正确的字段以删除不必使用的不必要的字段。

例如,如果我有2个集合。

用户集合:

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

User_data集合:

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

我的汇总代码:

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

希望输出:

{
    _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"
        }
    ]
}

我的输出:

{
    _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"
        }
    ]
}

我该如何解决这个问题?我已经尝试将$ project放入$ project中。但这对我没用。

0 个答案:

没有答案