MongoDB聚合$匹配第三个集合

时间:2016-12-14 13:37:26

标签: mongodb aggregation-framework

我有3个集合:User,Link和LinkView。

User:
{
    "_id": "ID",
    "username": "nick"
}

Link:
{
    "_id": "ID",
    "url": "http://google.com/",
    "user": {
        "$ref": "User",
        "$id": "ID",
        "$db": "database_name"
    }
}

LinkView:
{
    "_id": "ID",
    "created": "date",
    "link": {
        "$ref": "Link",
        "$id": "ID",
        "$db": "database_name"
    }
}

现在我想获得特定用户创建的LinkViews,但是当我尝试这个$ match时,它会返回空数据:

{
    $match: {
        "link.user.id" : "ID"
    }
}

如何按特定用户选择LinkView?

示例数据:

User:
{
    "_id" : "584e7fee1ccd5604a52ec901",
    "username" : "nick",
}

Link:
{
    "_id" : "584e814e1ccd5604ac025313",
    "url": "http://google.com/",
    "user": {
        "$ref": "User",
        "$id": "584e7fee1ccd5604a52ec901",
        "$db": "test"
    }
}

LinkView:
{
    "_id": "584e82191ccd560f0b690791",
    "created": "2016-12-12T09:54:10.000Z",
    "link": {
        "$ref": "Link",
        "$id": "584e814e1ccd5604ac025313",
        "$db": "test"
    }
},
{
    "_id": "584e82191ccd560f0b690795",
    "created": "2016-12-12T10:54:10.000Z",
    "link": {
        "$ref": "Link",
        "$id": "584e814e1ccd5604ac025313",
        "$db": "test"
    }
},
{
    "_id": "584e82301ccd560f0b690796",
    "created": "2016-12-12T11:54:10.000Z",
    "link": {
        "$ref": "Link",
        "$id": "584e814e1ccd5604ac025313",
        "$db": "test"
    }
}

聚合管道示例:

Array
(
[0] => Array
    (
        [$project] => Array
            (
                [hour] => Array
                    (
                        [$hour] => $created
                    )

            )

    )

[1] => Array
    (
        [$match] => Array
            (
                [link.user._id] => 584e7fee1ccd5604a52ec901
            )

    )

[2] => Array
    (
        [$group] => Array
            (
                [_id] => $hour
                [value] => Array
                    (
                        [$sum] => 1
                    )

            )

    )

)

1 个答案:

答案 0 :(得分:0)

要获取用户创建的链接视图,您需要一些 $lookup 管道,如下所示:

db.user.aggregate([
    { "$match": { "_id": "ID" } },
    {
        "$lookup": {
            "from": "link",
            "localField": "_id",
            "foreignField": "user",
            "as": "userlink"
        }
    },
    { "$unwind": "$userlink" },
    {
        "$lookup": {
            "from": "linkview",
            "localField": "userlink",
            "foreignField": "link",
            "as": "linkview"
        }
    }
])