Skip to content

Instantly share code, notes, and snippets.

@fathur
Last active August 12, 2017 11:49
Show Gist options
  • Select an option

  • Save fathur/3b6717baa9d4d568bc8eaf469c79938e to your computer and use it in GitHub Desktop.

Select an option

Save fathur/3b6717baa9d4d568bc8eaf469c79938e to your computer and use it in GitHub Desktop.
Mongo object to array
// 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