Adding new property to each document in a large collection

Justin picture Justin · May 31, 2011 · Viewed 8.6k times · Source

Using the mongodb shell, I'm trying to add a new property to each document in a large collection. The collection (Listing) has an existing property called Address. I'm simply trying to add a new property called LowerCaseAddress which can be used for searching so that I don't need to use a case-insensitive regex for address matching, which is slow.

Here is the script I tried to use in the shell:

for( var c = db.Listing.find(); c.hasNext(); ) {
   var listing = c.next();
   db.Listing.update( { LowerCaseAddress: listing.Address.toLowerCase() });
}

It ran for ~6 hours and then my PC crashed. Is there a better way to add a new property to each documentin a large collection (~4 million records)?

Answer

David Raab picture David Raab · May 31, 2011

you JavaScript didn't work, but the code below works. But don't knew how long it takes for 4 Million records.

db.Listing.find().forEach(function(item){
    db.Listing.update({_id: item._id}, {$set: { LowerCaseAddress: item.Address.toLowerCase() }})
})