首页 > 解决方案 > 用它的子字符串更新 mongoDB 中的字段

问题描述

我想缩短对象中的所有长描述。我已经搜索并阅读了很多文章,但我不知道如何在 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);
});

但这不起作用...

标签: mongodbmongodb-query

解决方案


这应该有效:

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

推荐阅读