在查找中使用匹配的mongo链接集合

时间:2016-09-05 17:08:38

标签: mongodb mongoose

我有两个收藏集 - ordersfeedback

订单:

{
    "restaurantId" : NumberInt(138), 
    "referenceNo" : "1980DBF5", 
    "orderId" : "1045593", 
    "userId" : NumberInt(6664960), 
    "userEmail" : "user@g.com", 
    "firstName" : "User"
}

反馈:

{
    "rating" : NumberInt(4), 
    "additionalComments" : "it is working", 
    "referenceNo" : "7D02097F", 
    "productId" : NumberInt(1), 
    "restaurantId" : NumberInt(138), 
    "orderType" : "1"
}

我需要在这两个集合上进行连接。

此外,还会对rating,referenceNo,userEmail,firstName进行过滤输入。 如何使用match来从两个集合中获取数据?

这是我的汇总查询:

[
    {
   "$lookup":
     {
       "from": "orders",
       "localField": "referenceNo",
       "foreignField": "referenceNo",
       "as": "data"
     }

    }
]

我在feedback模型上使用此查询。

我得到的数据是:

{
        "rating" : NumberInt(4), 
        "additionalComments" : "it is working", 
        "referenceNo" : "7D02097F", 
        "productId" : NumberInt(1), 
        "restaurantId" : NumberInt(138), 
        "orderType" : "1"
        "data": [{
        "restaurantId" : NumberInt(138), 
        "referenceNo" : "1980DBF5", 
        "orderId" : "1045593", 
        "userId" : NumberInt(6664960), 
        "userEmail" : "user@g.com", 
        "firstName" : "User"
    }]
    }

此外,是否可以在此处添加限制? 早些时候我在orders -

上使用它
mQuery.skip(Number(paginate.offset)).limit(Number(paginate.limit));

1 个答案:

答案 0 :(得分:1)

检查这是否有帮助......

db.feedbacks.aggregate([ {
     $lookup:                                          
        {
        from: "users",
        localField: "whatever",
        foreignField: "whatever",
        as: "data"                                       
    }},
{
  $unwind: "$data"
},
{
    $match:
         {
        "data.orderId":"1045593"}      //conditions
         },
{   
        $limit:1                       //limit
}
 ]);