如何在更新时仅更新数组的一个元素 [英] how to update just one element of array when updating

查看:106
本文介绍了如何在更新时仅更新数组的一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似以下内容的文档:

I have a doc like the following:

如您所见,我有一个数组实体:{1,3,4}

as you can see I have an array entity: {1,3,4}

现在我只想在该数组中将4更改为10并对其进行更新,因为我有以下代码:

Now I want to just change 4 to 10 in that array and update it for that I have the following code:

DBCollection coll = db.getCollection("test");
    BasicDBObject newDocument = new BasicDBObject();
    BasicDBObject searchQuery = new BasicDBObject().append("time", "20141105230000");

    coll.update(searchQuery, newDocument);
    String[] str = { "1", "3", "10" };
    DBObject updateMatchingElem = new BasicDBObject("$set",
            new BasicDBObject().append("entity", str));
    coll.update(searchQuery, updateMatchingElem);

但是这种方法不是一个好方法,因为我先删除了实体,然后再次插入了整个数组.无论如何,我可以将一个元素更改为4到10吗?

But this way is not a good way because I kind of remove entity and then insert the whole array again. Is there anyway that I can just change the one element like 4 to 10?

推荐答案

现在我只想在该数组中将4更改为10并更新它

您可以使用 $ 位置运算符.

You can do it in the following way, using the $ positional operator.

 //db.collection.update({"entity":4},{$set:{"entity.$":10}})
  DBObject find = new BasicDBObject( "entity", 4);
  DBObject set = new BasicDBObject( "entity.$", 10);
  DBObject update = new BasicDBObject().append("$set", set);
  coll.update(find, update);

请注意,即使数组中还有其他匹配元素,您最多也只能更新一个匹配数组元素.例如,如果数组中有两个4s,则只有 first 出现的4个会被更新.这就是位置运算符的工作方式.

Note that you can at most update only one single matching array element, even if there are other matching elements in the array. For instance, if there are two 4s in the array, only the first occurrence of 4 will get updated. This is how the positional operator works.

无论何时在更新查询中使用位置运算符,查找查询必须都包含查询的find部分中的字段.

Whenever you use the positional operator in the update query, the find query must contain the field in the find part of the query.

这篇关于如何在更新时仅更新数组的一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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