在单个查询中从mongodb中的2个集合中获取数据

时间:2018-10-09 15:19:11

标签: mongodb aggregation-framework

我想从2个独立的集合中获取数据,并通过一个查询基于date对结果进行排序。在mongodb中甚至可能吗?我有收藏集:

OrderType1

{
    "id": "1",
    "name": "Hello1",
    "date": "2016-09-23T15:07:38.000Z"
},
{
    "id": "2",
    "name": "Hello1",
    "date": "2015-09-23T15:07:38.000Z"
}

OrderType2

    {
        "id": "3",
        "name": "Hello3",
        "date": "2012-09-23T15:07:38.000Z"
    },
    {
        "id": "4",
        "name": "Hello4",
        "date": "2018-09-23T15:07:38.000Z"
    }

预期结果

[
    {
        "id": "3",
        "name": "Hello3",
        "date": "2012-09-23T15:07:38.000Z"
    },
    {
        "id": "2",
        "name": "Hello1",
        "date": "2015-09-23T15:07:38.000Z"
    },
    {
        "id": "1",
        "name": "Hello1",
        "date": "2016-09-23T15:07:38.000Z"
    },

    {
        "id": "4",
        "name": "Hello4",
        "date": "2018-09-23T15:07:38.000Z"
    }
]

现在,我想在按日期排序的单个查询中获取两种类型的orders

1 个答案:

答案 0 :(得分:1)

您可以尝试使用mongodb 3.6 及更高版本进行以下聚合,但我认为您应该使用两个查询,因为对于大型数据集$lookup管道,将违反BSON limit > 16mb 。但这也取决于您的$match条件或$limit。如果将它们应用于$lookup管道,那么您的聚合将可以完美地工作。

db.OrderType1.aggregate([
  { "$limit": 1 },
  { "$facet": {
    "collection1": [
      { "$limit": 1 },
      { "$lookup": {
        "from": "OrderType1",
        "pipeline": [{ "$match": { } }],
        "as": "collection1"
      }}
    ],
    "collection2": [
      { "$limit": 1 },
      { "$lookup": {
        "from": "OrderType2",
        "pipeline": [{ "$match": { } }],
        "as": "collection2"
      }}
    ]
  }},
  { "$project": {
    "data": {
      "$concatArrays": [
        { "$arrayElemAt": ["$collection1.collection1", 0] },
        { "$arrayElemAt": ["$collection2.collection2", 0] },
      ]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" } }
])