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

问题描述 投票:0回答:3

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

这给了我错误消息:

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

但这行不通...

mongodb mongodb-query
3个回答
1
投票

这应该有效:

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

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

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}});
});
© www.soinside.com 2019 - 2024. All rights reserved.