Last active
January 30, 2018 09:01
-
-
Save abn/6136750 to your computer and use it in GitHub Desktop.
Mongodb: convert a an array into a sub-document. Eg: { "field" : ["v1", "v2", ...], 'date' : $DATE } to { "field" : { "v1" : $DATE, "v2" : $DATE, ... } , 'date' : $DATE}
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
db.collection.find({ field : { $exists : true } }).forEach( function (x) { | |
var temp = {} | |
var count = 0 | |
for (var i in x.field) { | |
if (typeof x.field[i] == "string") { | |
// make sure index is a string | |
temp[x.field[i]] = x.date; | |
count++; | |
} | |
} | |
if (count > 0) { | |
// update only if not empty | |
x.field = temp; | |
db.collection.save(x); | |
} | |
delete temp; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment