Last active
August 12, 2017 11:49
-
-
Save fathur/3b6717baa9d4d568bc8eaf469c79938e to your computer and use it in GitHub Desktop.
Mongo object to array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Untuk collection disesuaikan antara comics_id, comics_en, atau comics_contest | |
| // sebaiknya dieksekusi sebelum jumlah like banyak (estimasi 1000) | |
| // takutnya kehabisan memory | |
| // @referensi: https://stackoverflow.com/questions/36164746/mongo-convert-embedded-document-to-array | |
| db.books.aggregate([ | |
| {"$unwind": "$sections"}, | |
| {"$match": { | |
| "sections.likes": { | |
| $exists: true, | |
| }, | |
| }}, | |
| {"$project": { | |
| "_id": true, | |
| "alias": true, | |
| "sections._id": true, | |
| "sections.alias": true, | |
| "sections.likes": true, | |
| "sections._like_type": { | |
| $type: "$sections.likes" | |
| }, | |
| }}, | |
| {"$match": { | |
| "sections._like_type": "object" | |
| }}, | |
| ]).forEach(function(document){ | |
| var idBook = document._id; | |
| var idSection = document.sections._id; | |
| var dumpLikes = []; | |
| var likes = document.sections.likes; | |
| for(a in likes) { | |
| dumpLikes.push(likes[a]); | |
| } | |
| // Jangan lupa ini juga diganti collection-nya | |
| db.books.updateOne({ | |
| '_id': idBook, | |
| "sections._id": idSection | |
| }, { | |
| $set: { | |
| "sections.$.likes": dumpLikes | |
| } | |
| }); | |
| // kosongin dulu untuk digunakan di iterasi berikutnya | |
| dumpLikes = []; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment