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

查看:39
本文介绍了将字符串附加到 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.

推荐答案

Starting Mongo 4.2, db.collection.update() 可以接受一个聚合管道,最终允许更新基于其当前值的字段:

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its current value:

// { a: "Hello" }
db.collection.update(
  {},
  [{ $set: { a: { $concat: [ "$a", "World" ] } } }],
  { multi: true }
)
// { a: "HelloWorld" }

  • 第一部分 {} 是匹配查询,过滤要更新的文档(在本例中为所有文档).

    • The first part {} is the match query, filtering which documents to update (in this case all documents).

      第二部分 [{ $set: { a: { $concat: [ "$a", "World" ] } } }] 是更新聚合管道(注意方括号表示使用聚合管道).$set ($addFields 的别名)是一个新的聚合运算符,在这种情况下,它替换字段的值(通过将 a 本身与后缀 "World" 连接起来).注意 a 是如何根据它自己的值($a)直接修改的.

      The second part [{ $set: { a: { $concat: [ "$a", "World" ] } } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set (alias of $addFields) is a new aggregation operator which in this case replaces the field's value (by concatenating a itself with the suffix "World"). Note how a is modified directly based on its own value ($a).

      不要忘记{ multi: true },否则只会更新第一个匹配的文档.

      Don't forget { multi: true }, otherwise only the first matching document will be updated.

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

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