How to update value of specific embedded document, inside an array, of a specific document in MongoDB?

你说的曾经没有我的故事 提交于 2019-11-27 19:54:32
RameshVel

You could still use $ positional operator to accomplish this. But you need to specify the objectid of the parent doc along with the _arrayid filter. The below command line query works fine

db.so.update({_id:ObjectId("4e719eb07f1d878c5cf7333c"),
              "array._arrayId":ObjectId("dsd87dsa9d87s9d7")},
              {$set:{"array.$.someField":"updated"}})

Here is RameshVel's solution translated to :

    DB db = conn.getDB( "yourDB" ); 
    DBCollection coll = db.getCollection( "yourCollection" );

    ObjectId _id = new ObjectId("4e71b07ff391f2b283be2f95");
    ObjectId arrayId = new ObjectId("4e639a918dca838d4575979c");

    BasicDBObject query = new BasicDBObject();
    query.put("_id", _id);
    query.put("array._arrayId", arrayId);

    BasicDBObject data = new BasicDBObject();
    data.put("array.$.someField", "updated");

    BasicDBObject command = new BasicDBObject();
    command.put("$set", data);

    coll.update(query, command);

...and this is how to do it with mongo-driver version >= 3.1 (mine is 3.2.2):

final MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURIString));
final MongoDatabase blogDatabase = mongoClient.getDatabase("yourDB");
MongoCollection<Document> postsCollection = blogDatabase.getCollection("yourCollection");

ObjectId _id = new ObjectId("4e71b07ff391f2b283be2f95");
ObjectId arrayId = new ObjectId("4e639a918dca838d4575979c");

Bson filter = Filters.and(Filters.eq( "_id", id ), Filters.eq("array._arrayId", arrayId));
Bson setUpdate = Updates.set("array.$.someField", "updated");
postsCollection.updateOne(postFilter, setUpdate);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!