正文
今天有一個需求,須要將aggregate的返回值轉換成一個字符串數組,這個事情頗爲費了一番腦筋,最後終於得以解決,參考這裏。java
db.users.aggregate([ { "$unwind": "$emails" }, { "$group": { "_id": "$emails.address" } } ]).map(function(el) { return el._id })
aggregate返回的老是對象,對這個結果直接使用map方法,對其進行轉換。應該參考的是這裏,使用了cursor的概念,這裏還有toArray的方法,這個方法也很是有用。mongodb
在aggregate的輸出後面,使用map方法,返回id
的值。數組
參考
https://stackoverflow.com/questions/33425565/how-to-return-array-of-string-with-mongodb-aggregation
https://examples.javacodegeeks.com/software-development/mongodb/mongodb-map-example/spa