mongodb - 用它的子字符串更新 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);
});
但这不起作用...
解决方案
这应该有效:
db.AssetDocument.find({
$where: "this.description.length > 500"
}).forEach(function(e){
e.description = e.description.substr(0,500);
db.AssetDocument.save(e);
});
推荐阅读
- reactjs - 如何使用 error.response.status 捕获打字稿错误
- apache-spark - spark AccumulatorV2 的问题。我是 apache spark 的新手,所以我不知道为什么会抛出这个问题
- javascript - 加一 - Leet 代码问题(简单) - 所有测试用例都通过了,除了 javascript 中的一个
- autodesk-forge - 使用 Forge API 在 Autodesk Construction Cloud 中添加或更改自定义属性的描述
- python - 使用 Django 获取图像上点击事件的坐标
- linux - 无法在 Linux 主机和 Linux VMware Workstation 来宾之间剪切和粘贴
- javascript - 我在 vs 代码上安装 create-react-app 但由于互联网问题安装停止,当我安装此错误时
- javascript - React App 没有编译我的图像或视频
- javascript - 所有选项卡上的 Window.onUnload
- java - 将 0 或 1 移到一侧,移位次数较少