MongoDB离开加入仅返回前1名

时间:2018-03-14 22:08:35

标签: mongodb mongoose mongodb-query aggregation-framework

我有以下2个系列。我试图在MongoDB中使用top 1 equavelant进行左连接。

// Vendors Collection
{
  "_id" : ObjectId("abc"),
  "vendorName" : "Jimmy Jones BBQ",
  "Address" : "3424 Western Ave...",
  "email" : "jimmy@mail.com"
},
{
  "_id" : ObjectId("def"),
  "vendorName" : "Bobby Jones BBQ",
  "Address" : "987 West Ave...",
  "email" : "bobby@mail.com"
},
{
  "_id" : ObjectId("ghi"),
  "vendorName" : "Henry smith BBQ",
  "Address" : "657 Western Ave...",
  "email" : "henry@mail.com"
}


// Sponsors Collection
{
  "_id" : ObjectId("5aa306b958056a9e2cc52e90"),
  "vendorID" : ObjectId("abc"),
  "name" : "Mary doe"
},
{
  "_id" : ObjectId("5aa306b958056a9e2cc52e90"),
  "vendorID" : ObjectId("abc"),
  "sponsor" : "mary doe"
},
{
  "_id" : ObjectId("5aa306b958056a9e2cc52e90"),
  "vendorID" : ObjectId("def"),
  "name" : "mary doe"
},
{
  "_id" : ObjectId("5aa306b958056a9e2cc52e90"),
  "vendorID" : ObjectId("ghi"),
  "name" : "mary doe"
}

这是我的总调用。

db.getCollection('vendors').aggregate([
    { "$match": { "retired": false } },
    { "$sort": { "name": 1 } }, 
    { "$lookup": {
         "from": "sponsors",
         "localField": "_id",
         "foreignField": "vendorID",
         "as": "sponsor"
      }
    },
    { "$unwind": "$sponsor" },
    { "$project": {
      "vendorName":1, 
      "Address":1, 
      "email":1
      "sponsor.name": 1
    } }
  ]).then(vendors => {
    console.log(vendors);
    // do stuff
  });

这样可行,但它会返回供应商ObjectId的多条记录(" abc"),因为有多个赞助商具有匹配的vendorID。我只想回到最前面。

// Results
{
  "_id" : ObjectId("abc"),
  "vendorName" : "Jimmy Jones BBQ",
  "address" : "3424 Western Ave...",
  "email" : "jimmy@mail.com",
  "sponsor" : {
      "name" : "Mary doe"
  }
},
{
  "_id" : ObjectId("abc"),
  "vendorName" : "Jimmy Jones BBQ",
  "address" : "3424 Western Ave...",
  "email" : "jimmy@mail.com",
  "sponsor" : {
    "name" : "Mary doe"
  }
},
,
{
  "_id" : ObjectId("def"),
  "vendorName" : "Bobby Jones BBQ",
  "address" : "987 West Ave...",
  "email" : "bobby@mail.com",
  "sponsor" : {
    "name" : "Jane doe"
  }
},
{
  "_id" : ObjectId("ghi"),
  "vendorName" : "Henry smith BBQ",
  "address" : "657 Western Ave...",
  "email" : "henry@mail.com",
  "sponsor" : {
    "name" : "John doe"
  }
}

我尝试使用$ group和$ limit但结果不合适。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

删除$unwind并将您的$project阶段更新为以下内容。

使用$let表达式使用$arrayElemAt创建前1个赞助商并映射名称。

{
  "$project":{
    "vendorName":1,
    "Address":1,
    "email":1,
    "sponsorName":{
      "$let":{
        "vars":{
          "sponsorone":{
            "$arrayElemAt":["$sponsor",0]
          }
        },
       "in":"$$sponsorone.name"
      }
    }
  }
}