简体   繁体   中英

Fetch data from 2 collections in mongodb in single query

I wanted to fetch data from 2 independent collections and sort the results based on date through a single query. Is that even possible in mongodb ? I have collections:

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"
    }

Expected Result

[
    {
        "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"
    }
]

Now, I want to fetch both types of orders in a single query sorted by date.

You can try below aggregation with mongodb 3.6 and above but I think you should use two queries because for the large data set $lookup pipeline will breach BSON limit of 16mb . But also It depends upon your $match condition or $limit . If they are applied to the $lookup pipeline then your aggregation would work perfectly.

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" } }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM