Mongodb查询需要改进

时间:2018-12-11 08:35:05

标签: mongodb mongodb-query aggregation-framework

大家好,

我正在做一个项目,并且正在使用MongoDB作为数据库。我有2个收藏集,如下所述:

评论

[{
    "_id":1,
    "name":"testname1",
    "email":"testmail1",
    "user_id":1
},
{
    "_id":2,
    "name":"testname1",
    "email":"testmail1",
    "user_id":1
},
{
    "_id":3,
    "name":"testname1",
    "email":"testmail1",
    "user_id":2
},
{
    "_id":4,
    "name":"testname1",
    "email":"testmail1",
    "user_id":2
},
{
    "_id":5,
    "name":"testname1",
    "email":"testmail1",
    "user_id":2
}]

和用户

[{
    "_id":1,
    "name":"testname1",
    "email":"testmail1",
},
{
    "_id":2,
    "name":"testname1",
    "email":"testmail1",
},
]

我想要以下格式的结果:

[{
    "_id":1,
    "name":"testname1",
    "email":"testmail1",
    "comment_ids":[1, 2]
},
{
    "_id":2,
    "name":"testname1",
    "email":"testmail1",
    "comment_ids":[3,4,5]
}]

这些是测试集合,我不想更改集合结构。 有人可以帮助我如何达到预期的结果。 我尝试了以下查询:

db.users.aggregate([{
   $lookup:
     {
       from: "comments",
       localField: "_id",
       foreignField: "user_id",
       as: "data"
     }
    }
])

查询的输出是:

{
    "_id" : 1,
    "name" : "testname1",
    "email" : "testmail1",
    "data" : [
        {
            "_id" : 1,
            "msg" : "test",
            "email" : "testmail1",
            "user_id" : 1
        },
        {
            "_id" : 2,
            "msg" : "test",
            "email" : "testmail1",
            "user_id" : 1
        }
    ]
}
{
    "_id" : 2,
    "name" : "testname1",
    "email" : "testmail1",
    "data" : [
        {
            "_id" : 3,
            "msg" : "test",
            "email" : "testmail1",
            "user_id" : 2
        },
        {
            "_id" : 4,
            "msg" : "test",
            "email" : "testmail1",
            "user_id" : 2
        },
        {
            "_id" : 5,
            "msg" : "test",
            "email" : "testmail1",
            "user_id" : 2
        }
    ]
}

2 个答案:

答案 0 :(得分:1)

只需对.dot使用_id表示法

db.users.aggregate([
  { "$lookup": {
    "from": "comments",
    "localField": "_id",
    "foreignField": "user_id",
    "as": "comment_ids"
  }},
  { "$addFields": { "comment_ids": "$comment_ids._id" }}
])

答案 1 :(得分:1)

我认为无需使用查找,因为您的评论集中已经有电子邮件和姓名。您可以直接使用group。与lookup相比,它将更快。这是示例

db.getCollection('comments').aggregate([
{
    $group:{
    "_id":"$user_id",
        "name":{$first:"$name"},
        "email":{$first:"$email"},
   comments:{$addToSet:"$_id"}
   }
}
])