MongoDB 收集多個陣列的資料:
{
"_id": ObjectId("61aa6bf1742b00f59b894eb7"),
"first": ["abc", "def", "ghi"],
"last": ["rst", "uvw", "xyz"],
"numb": ["12", "34", "56"]
}
陣列中的資料應采用以下格式的預期輸出:
{
"first": "abc",
"last": "rst",
"numb": "12"
},
{
"first": "def",
"last": "uvw",
"numb": "34"
},
{
"first": "ghi",
"last": "xyz",
"numb": "56"
}
uj5u.com熱心網友回復:
您可以使用$zip來“轉置”多個陣列(根據您的實際需要):
// {
// first: ["abc", "def", "ghi"],
// last: ["rst", "uvw", "xyz"],
// numb: ["12", "34", "56"]
// }
db.collection.aggregate([
{ $project: { x: { $zip: { inputs: ["$first", "$last", "$numb"] } } } },
// { x: [["abc", "rst", "12"], ["def", "uvw", "34"], ["ghi", "xyz", "56" ]] }
{ $unwind: "$x" },
// { x: [ "abc", "rst", "12" ] }
// { x: [ "def", "uvw", "34" ] }
// { x: [ "ghi", "xyz", "56" ] }
{ $replaceWith: {
$arrayToObject: { $zip: { inputs: [["first", "last", "numb"], "$x"] } }
}}
])
// { first: "abc", last: "rst", numb: "12" }
// { first: "def", last: "uvw", numb: "34" }
// { first: "ghi", last: "xyz", numb: "56" }
這個:
zips 3 個陣列,這樣相同索引處的元素將被分組到相同的子陣列中。$unwinds(爆炸/展平)這些子陣列。將結果陣列轉換為物件以適合您預期的輸出格式:
- 由
$zip(!再次)平的關鍵,我們要與陣列的價值觀聯系起來(鍵:["first", "last", "numb"]和值:"$x") - 以及
$replaceWith帶有$zip.
- 由
請注意,在 Mongo 之前4.2,您可以使用$replaceRoot代替$replaceWith.
uj5u.com熱心網友回復:
詢問
- 映射索引以將相同的索引成員組合到 1 個檔案
- 保持
_id還知道那些來自哪個檔案以及要排序的索引 - 對于每個索引從每個陣列中獲取元素
- 放松
- sort by
_id并index讓結果像在陣列中一樣排序
* 索引是使用最大陣列計算的,為了安全起見,如果您已經知道所有
{"$max": [{"$size": "$first"}, {"$size": "$last"}, {"$size": "$numb"}]}
陣列的大小相同,您可以將 : 替換為任何陣列的大小,例如(我們需要最大的陣列才能作業):
{"$size": "$first"}
測驗代碼在這里
aggregate(
[{"$project":
{"data":
{"$map":
{"input":
{"$range":
[0,
{"$max":
[{"$size": "$first"}, {"$size": "$last"}, {"$size": "$numb"}]}]},
"in":
{"_id": "$_id",
"index": "$$this",
"first": {"$arrayElemAt": ["$first", "$$this"]},
"last": {"$arrayElemAt": ["$last", "$$this"]},
"numb": {"$arrayElemAt": ["$numb", "$$this"]}}}}}},
{"$unwind": {"path": "$data"}},
{"$replaceRoot": {"newRoot": "$data"}},
{"$sort": {"_id": 1, "index": 1}},
{"$unset": ["index"]}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372914.html
標籤:数组 MongoDB mongodb-查询 放松
