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...

1

3 Answers 3

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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);
});

Comments

0
**This is working**
db.getCollection("AssetDocument").find({
   $where: "this.description.length > 100"
}).forEach(function(e){
   description = e.description.substr(0, 100);
   db.getCollection("AssetDocument").updateOne({_id: e._id}, 
     {"$set": {"description": description}});
});

Comments

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.