0

I have 2 subproperties of a document and want to move all properties from one to another, but AFTERWARDS I want to erase the empty property.

Now I know the $rename command can be used to move each property from one place to another, but I also want the empty object destroyed, but only after the move.

So how does one do this?

Here is an example:

{
    _id : ObjectID,
    firstProperty : {
        value0 : 1,
        value1 : 2
    },
    secondProp: {
        value5 : 3,
        value6 : 4
    }
}

Then after process:

{
    _id : ObjectID,
    firstProperty : {
        value0 : 1,
        value1 : 2,
        value5 : 3,
        value6 : 4
    }
}
Discipol
  • 3,137
  • 4
  • 22
  • 41
  • Example before and after docs would be really helpful. – JohnnyHK Nov 16 '13 at 16:55
  • 1
    Still -- just do it in two steps, or read the entire object and save the entire object. Given the amount of change you're likely introducing to the structure, it may be necessary anyway. – WiredPrairie Nov 16 '13 at 18:07

1 Answers1

0

Here is how you can do this in mongoshell, I hope it would not be hard to convert it to node.js because this is the same js.

Your document:

{
    _id : 1,
    firstProperty : {
        value0 : 1,
        value1 : 2
    },
    secondProp: {
        value5 : 3,
        value6 : 4
    }
}

Copying info from the second property:

var a = db.b.findOne({_id : 1},{secondProp : 1})

Preparing an object to set it with update:

var setObj = {};
for(var i in a.firstProperty){
   setObj['firstProperty.'+i] = a.secondProp[i];
}

And update with $set, $unset

db.b.update(
  {_id : 1},
  {$unset : {secondProp : 1}, $set : setObj }
)
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753