Skip to content

Instantly share code, notes, and snippets.

@abn
Last active January 30, 2018 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abn/6136750 to your computer and use it in GitHub Desktop.
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}
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