collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).pretty()
this give me documents structure:
{ "_id" : "ejbftz7eegbbpwjaw", "title" : "title", "reference" : "8uujf9pivpga37oqc", "parent" : "v7djzq859xx4kvkpi", "ancestors" : [ "v7djzq859xx4kvkpi" ] }
now have transform documents in way:
- move title new document ,
- update
parent
id new document - push new id ancestors (in first position!)
the result should be:
{ "_id" : "gzrn4ndkfeewb8eye", // new document "title" : "title", // moved title "parent" : "v7djzq859xx4kvkpi", "ancestors" : [ "v7djzq859xx4kvkpi" ] }, { "_id" : "ejbftz7eegbbpwjaw", // removed title "reference" : "8uujf9pivpga37oqc", "parent" : "gzrn4ndkfeewb8eye", // update parent id new id "ancestors" : [ "gzrn4ndkfeewb8eye", // add new id @ first pos "v7djzq859xx4kvkpi" ] }
so i'm thinking of that:
collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).foreach(function(doc) { // data source var id = doc.id; var title = doc.title; var parent = doc.parent; // insert new document var newid = collection.insert({ title: title, parent: parent, ancestors: [parent] }); // update source document if (newid) { collection.update( { _id: id }, { $set: { parent: newid }, // update parent id $push: { ancestors: newid } // update ancestors array $unset: { title: '' } // remove title } ); } });
- but doing
$push
append id instead of prepending it. - is correct use
if (newid) {}
or should put part in callback function ofinsert
?
if there improvements possible, please let me know.
1) try $position variable https://docs.mongodb.org/master/reference/operator/update/position/#up._s_position
2) same mongodb insert method return new _id created.
regards
Comments
Post a Comment