在单个查询中从mongodb中的2个集合中获取数据 [英] Fetch data from 2 collections in mongodb in single query
问题描述
我想从2个独立的集合中获取数据,并通过一个查询根据日期
对结果进行排序。在 mongodb
中甚至可能吗?我有收藏集:
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"
}
预期结果
[
{
"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.
推荐答案
您可以在mongodb 3.6 及更高版本下面尝试聚合,但我认为您应该使用两个查询因为对于大型数据集 $ lookup
管道将违反 BSON限制 为 16mb 。但这也取决于您的 $ match
条件或 $ limit
。如果将它们应用于 $ lookup
管道,那么您的聚合将可以正常工作。
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" } }
])
这篇关于在单个查询中从mongodb中的2个集合中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!