Mongodb中的$ lookup返回空数组

时间:2018-05-05 23:20:49

标签: mongodb

我正在开发一个mongodb数据库项目。我有两个集合:“用户”和“评论”。我想使用$ lookup将“user”中的一些信息组合到“comments”。

这是我的“用户”集合:

db.user.insert(
[
    { user_id: 1, fname: "D", lname: "Lei", email: "d@m.edu" },
    { user_id: 2, fname: "R", lname: "Wick", email: "rn@m.edu" },
    { user_id: 3, fname: "B", lname: "Elfs", email: "bs@m.edu" },
    { user_id: 4, fname: "A", lname: "Losh", email: "a@me.edu" },
    { user_id: 5, fname: "T", lname: "Ph", email: "p_thi@m.edu" }

]
)

这是“评论”集合:

db.comments.insert(
[
{blog_ID: 37, user_ID: 4, texts: 'comment ...', date_posted: '2016-1-1'},
{blog_ID: 3, user_ID: 4, texts: 'comment ...', date_posted: '2009-7-4'},
{blog_ID: 15, user_ID: 3, texts: 'comment ...', date_posted: '2017-6-4'},
{blog_ID: 4, user_ID: 4, texts: 'comment ...', date_posted: '2012-3-11'},
{blog_ID: 38, user_ID: 5, texts: 'comment ...', date_posted: '2005-11-6'},
{blog_ID: 2, user_ID: 1, texts: 'comment ...', date_posted: '2011-10-11'},
{blog_ID: 46, user_ID: 4, texts: 'comment ...', date_posted: '2014-12-13'},
{blog_ID: 31, user_ID: 2, texts: 'comment ...', date_posted: '2012-11-26'},
{blog_ID: 26, user_ID: 3, texts: 'comment ...', date_posted: '2006-10-28'},
{blog_ID: 47, user_ID: 3, texts: 'comment ...', date_posted: '2018-1-15' }
]
)

这是我的问题:

   db.comments.aggregate([

    {$match: {user_ID:4}},        
    {$group: {_id:"$user_ID", count:{$sum:1}}},
    {$lookup:{
                from: "user",
                localField: "user_ID",
                foreignField: "user_id",
                as: "combine"
            }
     }


])

“combine”数组为空:

enter image description here

1 个答案:

答案 0 :(得分:0)

管道的第二阶段($group阶段)正在用user_ID字段替换原始_id字段。因此,您必须在_id阶段使用localField作为$lookup

db.comments.aggregate([
    {$match: {user_ID:4}},        
    {$group: {_id:"$user_ID", count:{$sum:1}}},
    {$lookup:{
                from: "user",
                localField: "_id",
                foreignField: "user_id",
                as: "combine"
            }
     }
])