mongo db根据连接条件选择2个表中的所有行

时间:2017-09-23 17:57:18

标签: node.js mongodb aggregate mongojs

我有2张桌子

 useraverage
    id
    average



 usersdetails
    id
    name
    address

output
id
name
address
average

我尝试了查找,但没有返回数据。

db.userdetails.aggregate([
    {
      $lookup:
        {
          from: "useraverage",
          localField: "id",
          foreignField: "id",
          as: "useraverage"
        }
   }
    ],function (err, result) {
        console.log(result);
        res.json(result);
    });

1 个答案:

答案 0 :(得分:0)

您使用的是MongoDB的_id还是您拥有的?如果您使用的是第一个选项,则查询应如下所示:

    `db.userdetails.aggregate([
     {
      $lookup:
        {
          from: "useraverage",
          localField: "_id",
          foreignField: "_id",
          as: "useraverage"
        }
    },
    {$unwind : "$useraverage"},
    {$project : {
       name : 1,
       address : 1,
       average: "$useraverage.average"
       }}
     ],function (err, result) {
        console.log(result);
        res.json(result);
     });`