MongoDB更新.尝试从另一个属性设置一个字段 [英] MongoDB update. Trying to set one field from a property of another

查看:139
本文介绍了MongoDB更新.尝试从另一个属性设置一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的事情很简单,但是我找不到如何赋予一个字段另一个值的方法.

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更新.尝试从另一个属性设置一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆