使用子字符串更新mongoDB中的字段

时间:2018-12-13 11:40:47

标签: mongodb mongodb-query

我想在对象中缩短所有长的描述。 我已经搜索并阅读了许多文章,但是我不知道如何在mongoDB中完成此简单任务。 我要实现的目标在SQL中很简单:

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

可以请人帮我在MongoDB中做到这一点吗?

我已经尝试过了:

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

这给了我errmsg:The dollar ($) prefixed field '$substr' in 'metadata.description.$substr' is not valid for storage.

然后我尝试了这个:

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

但这不起作用...

2 个答案:

答案 0 :(得分:1)

这应该有效:

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

答案 1 :(得分:1)

您可以使用

db.AssetDocument.find({}).forEach(function(e)
{ if(e.description.length<500) 
e.metadata.description=  e.metadata.description.substr(0,500)
 db.AssetDocument.save(e);
});
相关问题