将字符串追加到MongoDB中现有字段的末尾 [英] Append a string to the end of an existing field in MongoDB

查看:759
本文介绍了将字符串追加到MongoDB中现有字段的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档,其中的字段包含一个很长的字符串.我需要将另一个字符串连接到该字段中已经包含的字符串的末尾.

I have a document with a field containing a very long string. I need to concatenate another string to the end of the string already contained in the field.

我现在要做的是从Java中获取文档,在字段中提取字符串,将字符串附加到末尾,最后用新的字符串更新文档.

The way I do it now is that, from Java, I fetch the document, extract the string in the field, append the string to the end and finally update the document with the new string.

问题:字段中包含的字符串很长,这意味着在Java中检索和使用此字符串需要花费时间和资源.此外,这是每秒执行几次的操作.

The problem: The string contained in the field is very long, which means that it takes time and resources to retrieve and work with this string in Java. Furthermore, this is an operation that is done several times per second.

我的问题:是否有一种方法可以将字符串连接到现有字段,而不必先获取(db.<doc>.find())该字段的内容?实际上,我想要的只是(field.contents += new_string).

My question: Is there a way to concatenate a string to an existing field, without having to fetch (db.<doc>.find()) the contents of the field first? In reality all I want is (field.contents += new_string).

我已经使用Javascript和eval进行了这项工作,但是我发现,MongoDB在执行javascript时会锁定数据库,这会使整个应用程序变得更慢.

I already made this work using Javascript and eval, but as I found out, MongoDB locks the database when it executes javascript, which makes the overall application even slower.

推荐答案

例如(附加在开头,同一个故事):

For example (it's append to the start, the same story ):

之前

{"_id":ObjectId("56993251e843bb7e0447829d"),名称":伦敦 城市",城市":伦敦"}

{ "_id" : ObjectId("56993251e843bb7e0447829d"), "name" : "London City", "city" : "London" }

db.airports
   .find( { $text: { $search: "City" } })
   .forEach(
       function(e, i){ 
           e.name='Big ' + e.name; 
           db.airports.save(e);
       }
    )

之后:

{"_id":ObjectId("56993251e843bb7e0447829d"),名称":大伦敦 城市",城市":伦敦"}

{ "_id" : ObjectId("56993251e843bb7e0447829d"), "name" : "Big London City", "city" : "London" }

这篇关于将字符串追加到MongoDB中现有字段的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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