[英]MongoDB aggregation, combining 2 arrays in round-robin fashion
我在 MongoDB 集合中有數據,看起來像這樣:
[
{
"_id": 1,
"type": "big",
"fields": [11, 12, 13],
"items": [21, 22, 23]
},
{
"_id": 2,
"type": "small",
"fields": [14, 15],
"items": [24, 25]
},
{
"_id": 3,
"type": "small",
"fields": [],
"items": [41, 42]
},
{
"_id": 4,
"type": "small",
"fields": [31, 32, 33],
"items": []
}
]
我的任務是根據這樣的程序返回數據:
對於集合中的每個文檔,從其
fields
(如果有)中獲取 1 個值,並從其items
(如果有)中獲取 1 個值。 將所有結果連接到一個數組中。
人們可以將其總結為以“循環”方式從每個文檔中保存的兩個 arrays 中選擇數據。
我將如何在 MongoDB 聚合查詢中實現這一點? 這個邏輯在連接到 Mongo 服務器的客戶端中並不難實現,但我想讓 Mongo 負責分頁(使用$skip
和$limit
)。 我正在使用 MongoDB 4.4。
結果數據看起來像這樣:
[
{
"value": 11,
"type": "field",
"fromId": 1
},
{
"value": 21,
"type": "item",
"fromId": 1
},
{
"value": 14,
"type": "field",
"fromId": 2
},
{
"value": 24,
"type": "item",
"fromId": 2
},
{
"value": 41,
"type": "item",
"fromId": 3
},
{
"value": 31,
"type": "field",
"fromId": 4
},
]
如果我理解你的問題是正確的; 這應該是一個可行的 pipe。 要實現隨機功能,您只需調整傳遞給 $arrayElemAt 的索引
https://mongoplayground.net/p/PPXV6fTSwHP
db.collection.aggregate([
{$project: {
types: [
{type: "field", values: "$fields"},
{type: "item", values: "$items"}
]
}},
{$unwind: '$types'},
{$project: {
_id: 0,
value: {$arrayElemAt: ['$types.values', 0]},
type: '$types.type',
fromId: '$_id'
}},
{$match: {
value: {$exists: true}
}}
])
隨機化看起來像這樣: https://mongoplayground.net/p/qi1Ud53J6yv
db.collection.aggregate([
{$project: {
types: [
{type: "field", values: "$fields"},
{type: "item", values: "$items"}
]
}},
{$unwind: '$types'},
{$project: {
_id: 0,
value: {$arrayElemAt: [
'$types.values',
{$floor: {$multiply: [{$rand: {}}, {$size: '$types.values'}]}}
]},
type: '$types.type',
fromId: '$_id'
}},
{$match: {
value: {$exists: true}
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.