需要在mongo查询中执行$ lookup和$ match后获得匹配的记录

时间:2018-12-04 15:15:57

标签: mongodb mongodb-query aggregation-framework lookup aggregation

汇总查询:

db.status.aggregate([
  {
    "$lookup": {
      "from": "order",
      "localField": "orderId",
      "foreignField": "_id",
      "as": "output"
    }
  },
  {
    "$match": {
      "output.status": "PICKUP_COMPLETE"
    }
  },
  {
    "$project": {
      "orderId": 1,
      "orderStatus": {
        "$filter": {
          "input": "$orderStatus",
          "as": "orderStatus",
          "cond": { "$eq": ["$$orderStatus.status", "PICKUP_COMPLETE"] }
        }
      }
    }
  }
])

状态收集记录:

{
  "_id": ObjectId("59490963d683587d32c278ac"),
  "orderId": ObjectId("5949095ed683587d32c278a9"),
  "tenantId": "D-mart",
  "orderStatus": [
    {
      "status": "ESTIMATES_RECEIVED",
      "updatedAt": "June 20th 2017, 6:39:15 am"
    },
    { "status": "RECEIVED_BY_LMA", "updatedAt": "June 20th 2017, 6:45:25 am" },
    { "status": "ORDER_CONFIRMED", "updatedAt": "June 20th 2017, 6:45:25 am" }
  ]
}

我需要基于orderId字段从订单收集和状态收集中获取所有匹配的记录,并在orderStatus数组中匹配状态为“ PICKUP_COMPLETE”的记录(任何一个数组对象都应具有此状态)。

上面的查询工作正常,将基于orderId的两个集合连接在一起,但是它只返回第一个匹配的记录。即

{
  "_id": ObjectId("5a7e0a06a33f4900015c14d7"),
  "orderId": ObjectId("5a7e0a06a33f4900015c14d6"),
  "orderStatus": [
    {
      "status": "PICKUP_COMPLETE",
      "updatedAt": "February 14th 2018, 11:51:09 am"
    }
  ]
}

我想知道如何获取此类匹配记录的整个列表...

0 个答案:

没有答案