问题描述
我想做的事情很简单,但是我找不到如何赋予一个字段另一个值的方法.
What I'm trying to do is pretty straightforward, but I can't find out how to give one field the value of another.
我只想用一个字段的字符数更新一个字段.
I simply want to update one field with the character count of another.
db.collection.update({$exists:true},{$set : {field1 : field2.length}})
我尝试给它加上点符号
db.collection.update({$exits:true},{$set : {field1: "this.field2.length"}})
以及使用javascript语法
As well as using javascript syntax
db.collection.update({$exits:true},
{$set : {field1: {$where : "this.field2.length"}})
但是只是复制了字符串并分别得到一个"notOkforstorage".有帮助吗?
But just copied the string and got a "notOkforstorage" respectively. Any help?
更新:当我通过ID查询时,我只会得到"notOkforStorage":
Update:I only get the "notOkforStorage" when I query by ID:
db.collection.update({_id:ObjectID("38289842bbb")},
{$set : {field1: {$where :"this.field2.length"}}})
推荐答案
尝试以下代码:
db.collection.find(your_querry).forEach(function(doc) {
doc.field1 = doc.field2.length;
db.collection.save(doc);
});
您可以使用your_querry
选择仅原始集合的一部分来执行更新.如果要处理整个集合,请使用your_querry = {}
.
You can use your_querry
to select only part of the original collection do perform an update. If you want to process an entire collection, use your_querry = {}
.
如果您希望所有操作都是原子操作,请使用update
而不是save
:
If you want all operations to be atomic, use update
instead of save
:
db.collection.find( your_querry, { field2: 1 } ).forEach(function(doc) {
db.collection.update({ _id: doc._id },{ $set: { field1: doc.field2.length } } );
});
这篇关于MongoDB更新.尝试从另一个属性设置一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!