我想缩短我的对象中的所有长描述。 我搜索并阅读了很多文章,但我不知道如何在 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);
});
但这行不通...
这应该有效:
db.AssetDocument.find({
$where: "this.description.length > 500"
}).forEach(function(e){
e.description = e.description.substr(0,500);
db.AssetDocument.save(e);
});
你可以像
一样使用db.AssetDocument.find({}).forEach(function(e)
{ if(e.description.length<500)
e.metadata.description= e.metadata.description.substr(0,500)
db.AssetDocument.save(e);
});
**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}});
});