javascript - mongodb: moving field to new document and update fields and array -


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:

  1. move title new document ,
  2. update parent id new document
  3. 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             }         );           }  }); 
  1. but doing $push append id instead of prepending it.
  2. is correct use if (newid) {} or should put part in callback function of insert?

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