谢谢!多个数组元素可以具有字段"Y",如编辑的代码所示.我只想编辑特定元素的"Y"字段.解决方案要使用Java驱动程序执行此操作,可以执行以下操作:DBObject queryForElem = new BasicDBObject("array", new BasicDBObject("$elemMatch", new BasicDBObject("id", "3456")));DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));coll.update(queryForElem, updateMatchingElem);鉴于这有点笨拙,您可以改用QueryBuilder,这使您更具可读性:DBObject queryForElem = QueryBuilder.start("array").elemMatch(new BasicDBObject("id", "3456")).get();DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));coll.update(queryForElem, updateMatchingElem);Say I have the following mongo object in a database:{ "_id" : ObjectId("4f904ebb5bebd4375b759c90"), "findme" : "someValue", "array" : [ { "id" : "1234" "Y" : "0" }, { "id" : "3456" "Y" : "0" }, { "id" : "5678" "Z" : "0" } ]}I know that i can change the array contents with the following dot notation accessors in java...BasicDBObject change = new BasicDBObject("findme", "someValue"); BasicDBObject setDoc = new BasicDBObject(); setDoc.append("array.0.Y", "0"); setDoc.append("array.1.Y", "0"); setDoc.append("array.2.Z", "0"); BasicDBObject account = new BasicDBObject("$set", setDoc);coll.update(change, account);But how would I change the value of "3456"'s "Y" if I only knew that the id was "3456" and not that it was at index 1 in "array"? I would really like to accomplish this entirely within the creation of these query objects and the update method... In other words I'd rather not pull the whole object out and iterate through the "array" to find out it's position.Thanks!Edit: Multiple array elements can have the field "Y" as shown in the edited code. I only want to edit a specific element's "Y" field. 解决方案 To do this using the Java driver, you can do the following:DBObject queryForElem = new BasicDBObject("array", new BasicDBObject("$elemMatch", new BasicDBObject("id", "3456")));DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));coll.update(queryForElem, updateMatchingElem);Given that that's a bit unwieldy, you can use the QueryBuilder instead, which gives you a little more readability:DBObject queryForElem = QueryBuilder.start("array").elemMatch(new BasicDBObject("id", "3456")).get();DBObject updateMatchingElem = new BasicDBObject("$set", new BasicDBObject("array.$.Y", "1"));coll.update(queryForElem, updateMatchingElem); 这篇关于Java中mongo数组中的访问元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 16:03