0

I have an object in my document like this:

revisions: {
  <revisionId>: {
    ...
    someProperty: { ... },
  },
  ...
}

I would like to remove someProperty from every nested object in revisions object (i.e. iterate through all the object revisionId keys). I'm asking because if it's not possible I'd rather convert this to an array than do it on the server and possibly overwrite any updates in the mean time.

I tried $unset but I'm only aware of the $[] operator which only works for arrays e.g.

$unset: {
  'revisions.$[].someProperty': 1
}

Thanks

1
  • 1
    Converting this structure to an array based one makes total sense. Go for that approach! Commented Oct 14, 2018 at 13:36

1 Answer 1

1

You're almost there:

{ $unset: { someProperty: "" } }

The value doesn't matter from memory

You could then use a cursor to iterate through each doc and remove the unwanted property.

db.collection.find().forEach(<function>)

EDIT: Sorry, realising it's a nested model with arbitrary key for the top level property, makes it more tricky.

t.forEach(function( row) {
    var newRevisions = [];
    row.revisions.fields.forEach( function( revision ){
        delete revision.someProperty;
        newRevisions.push(revision);
    } )
    t.update(
        { _id: row._id }, 
        { "$set": { "revisions": newRevisions} }
    );
});

Huge caveat, totally untested, but should give you starting point.

  1. For each row
  2. For each revision in revisions object
  3. Remove the someProperty property
  4. Set the revisions property back the collection based on _id
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is not really what I'm after as I try and avoid any DB manipulation on the server as it can overwrite changes that happened in the mean time through async operations or other servers in a cluster so think I will have to use an array instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.