0

I would like to shorten all long descriptions in my object. I have searched and read many articles but I can't figure out how to do this simple task in mongoDB. What I am trying to achieve would be simple in SQL:

UPDATE AssetDocument SET description = substr(description, 0, 500) WHERE length(description) > 500

Can please someone help me do this in MongoDB?

I have tried this:

db.AssetDocument.updateMany(
{$where: "this.metadata.description.length > 500"},
{$set: { "metadata.description": { $substr: ["metadata.description", 0, 500]}}});

This gives me errmsg: The dollar ($) prefixed field '$substr' in 'metadata.description.$substr' is not valid for storage.

Then I tried this:

db.AssetDocument.find({
  $where: "this.metadata.description.length > 500"
}).forEach(function(e){
  e.metadata.description = {$substr: [e.metadata.description, 0, 500]};
  db.AssetDocument.save(e);
});

But this doesn't work...

Lukáš Budoš
  • 271
  • 1
  • 3
  • 11
  • Possible duplicate of [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – Ashh Dec 13 '18 at 11:56

2 Answers2

1

This should work:

db.AssetDocument.find({
  $where: "this.description.length > 500"
}).forEach(function(e){
  e.description = e.description.substr(0,500);
  db.AssetDocument.save(e);
});
Pubudu Jayawardana
  • 2,250
  • 1
  • 13
  • 18
1

you can use like

db.AssetDocument.find({}).forEach(function(e)
{ if(e.description.length<500) 
e.metadata.description=  e.metadata.description.substr(0,500)
 db.AssetDocument.save(e);
});
Vipul Pandey
  • 1,507
  • 11
  • 20