MongoDB:使用$ concat更新字段值时出现问题 [英] MongoDB: Problems using $concat to update the value of a field
问题描述
我正尝试通过将其与文字字符串连接来更新MongoDB集合中字段的值。除此之外,该字段是一个整数,我想在前面添加一个 0,因此它将成为一个字符串。
I'm trying to update the value of a field in a MongoDB collection by concatenating it with a literal string. Besides this, the field is an integer, and I want to add a "0" in front, so it will became a string.
我已经读到可以不会在单个更新指令中使用字段的旧值,因此我使用的是 forEach()方法。
I've read that I can't use the old value of the field in a single update instruction, so I'm using a forEach() method.
这里是代码:
db.col_1.find({"field_1": {$lt: 10000}}).forEach( function(i){
db.col_1.update({_id: i._id},
{$set: { "field_1": {$concat: ["0", i.field_1]}}}
)
});
返回结果为:
The dollar ($) prefixed field '$concat' in 'field_1.$concat' is not valid for storage.
我确定我没有正确编写$ concat命令,有什么办法
I'm sure I'm not writting the $concat command properly, is there any way to do this?
推荐答案
$ concat是聚合管道,而不是更新运算符/修饰符。
$concat is an aggregation pipeline, not an update operator/modifier.
似乎您可以通过以下操作来实现:
It seems that what you're trying to do can be achieved by doing the following:
db.col_1
.find({ "field_1": { $lt: 10000 } })
.forEach( function(i) {
db.col_1.update(
{ _id: i._id },
{ $set: { "field_1": "0" + i.field_1 } }
)
});
这篇关于MongoDB:使用$ concat更新字段值时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!