0

Given the following document, I want to rename "Doc" to "doc". I thought maybe I could use $rename within a forEach but no such luck.

db.getCollection('Docs').find({}).forEach(
function(doc){        
    doc.history.forEach(function(d2){                        
        var id = d2._id
       db.collection.update(d2, {$rename:{"Doc": "doc"}});
       print(d2);
    })                
}
)


{
"_id": "ObjectId(\"5b85c223e959480ea8b2c6d2",
"history"[{
        "Doc": {},
        "Doc": {},
        "Doc": {}
    }
]
}
jbassking10
  • 833
  • 4
  • 15
  • 42
  • 1
    Possible duplicate of [MongoDB rename database field within array](https://stackoverflow.com/questions/9122966/mongodb-rename-database-field-within-array) – dnickless Oct 09 '18 at 20:18
  • This is indeed a duplicate, and there are answers that would work for you in your case (specifically see Eli Gassert's answer midway down the page. – J. Rickman Oct 09 '18 at 20:27
  • I had tried that example and couldn't get it to work. I'm using Robo 3T. The only message I get back is Script executed successfully, but there are no results to show. Maybe I'm not understanding it correctly. The loop is going through item.Value.Tiers. Is Value.Tiers an internal object? – jbassking10 Oct 09 '18 at 20:45
  • This worked for me: db.Docs.find({ 'history': { $exists: 1 } }).snapshot().forEach(function(item) { item.history.forEach(function(item2){ item2.doc = item2.Doc; delete item2["Doc"]; print(item2); }) db.Docs.save(item); }); – jbassking10 Oct 09 '18 at 21:09

1 Answers1

0

This ended up working for me:

db.Docs.find({ 'history': { $exists: 1 } }).snapshot().forEach(function(item)
{      
    item.history.forEach(function(item2){        
        item2.doc = item2.Doc;
        delete item2["Doc"];
        print(item2);
    })

    db.Docs.save(item);
}); 
jbassking10
  • 833
  • 4
  • 15
  • 42