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

后端 未结 4 2031
孤城傲影
孤城傲影 2020-12-03 01:45

I have the following structure in my document:

{
  _id : ObjectId(\"43jh4j343j4j\"), 
  array : [
            { 
              _arrayId : ObjectId(\"dsd87ds         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 02:26

    ...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 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);
    

提交回复
热议问题