一、概述
MongoDB unwind是MongoDB中一個非常強大的操作,它能夠將數組類型的數據分解成單獨的文檔,從而方便對這些文檔進行CRUD操作。
通常情況下,我們使用MongoDB的聚合操作的時候,需要使用unwind操作將數組類型的數據顯示為多個文檔,然後才能夠進行下一步的操作。
二、使用場景
unwind操作非常適合解決一些特定的場景問題,例如:
1、數組類型的排序問題
假設我們有這樣一張表:
{ "_id" : 1, "name" : "John Smith", "age" : 25, "hobbies" : [ "reading", "swimming", "travelling" ] }
現在我們想要根據hobbies字段中的內容進行排序,這個時候就可以使用unwind操作將hobbies展開為多個文檔,然後進行排序操作。
db.test.aggregate([ { $unwind : "$hobbies" }, { $sort : { name : 1, "hobbies" : -1 } } ]);
2、數組類型的統計問題
假設我們有這樣一張表:
{ "_id" : 1, "name" : "John Smith", "age" : 25, "scores" : [ 90, 80, 70 ] }
現在我們想要統計每個人的平均分數,這個時候就可以使用unwind操作將scores展開為多個文檔,然後進行平均分數的統計操作。
db.test.aggregate([ { $unwind : "$scores" }, { $group : { _id : "$name", avgScore : { $avg : "$scores" } } } ]);
3、數組類型的過濾查詢問題
假設我們有這樣一張表:
{ "_id" : 1, "name" : "John Smith", "age" : 25, "results" : [ { "subject" : "math", "score" : 80 }, { "subject" : "english", "score" : 90 } ] }
現在我們想要查詢math分數大於80分的人,這個時候就可以使用unwind操作將results展開為多個文檔,然後進行過濾查詢操作。
db.test.aggregate([ { $unwind : "$results" }, { $match : { "results.subject" : "math", "results.score" : { $gt : 80 } } } ]);
三、unwind操作的語法
unwind操作的語法非常簡單,只需要在聚合操作中使用$unwind操作符即可。
db.collection.aggregate([ { $unwind : "arrayFieldName" } ]);
其中,arrayFieldName表示需要拆分的數組類型的字段名稱。
四、unwind操作的參數及含義
$unwind操作支持多個參數,並且每個參數都有特定的含義。
1、path參數
path參數是unwind操作必須的參數,它用於指定需要展開的數組字段名稱。
db.collection.aggregate([ { $unwind : "$arrayFieldName" } ]);
2、includeArrayIndex參數
includeArrayIndex參數表示是否需要將數組下標信息包含在展開後的文檔中,默認情況下這個參數為false。
db.collection.aggregate([ { $unwind : { path: "$arrayFieldName", includeArrayIndex: "string" } } ]);
3、preserveNullAndEmptyArrays參數
preserveNullAndEmptyArrays參數表示是否需要展開空數組。
db.collection.aggregate([ { $unwind : { path: "$arrayFieldName", preserveNullAndEmptyArrays: true } } ]);
4、unwind操作的示例代碼
假設我們有這樣一張表:
{ "_id" : 1, "name" : "John Smith", "age" : 25, "hobbies" : [ "reading", "swimming", "travelling" ] }
現在我們來看看如何使用unwind進行展開操作:
db.test.aggregate([ { $unwind : "$hobbies" } ]);
執行以上操作後,展開後的文檔如下:
{ "_id" : 1, "name" : "John Smith", "age" : 25, "hobbies" : "reading" }, { "_id" : 1, "name" : "John Smith", "age" : 25, "hobbies" : "swimming" }, { "_id" : 1, "name" : "John Smith", "age" : 25, "hobbies" : "travelling" }
五、總結
通過以上的介紹,我們可以知道,unwind操作是MongoDB中非常實用的一個操作符,它可以將數組類型的數據展開成多個文檔,方便對這些文檔進行下一步的操作。需要注意的是,在使用unwind操作的時候,一定要先考慮清楚自己的需求,然後再合理的使用相關參數進行操作,這樣可以避免一些無謂的麻煩。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/198377.html