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

后端 未结 4 2035
孤城傲影
孤城傲影 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:35

    Seeing as none of the answers actually explain how to do this a) in Java and b) for multiple fields in a nested array item, here is the solution for mongo-java-driver 3.12.3.

    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.model.Filters;
    import com.mongodb.client.model.Updates;
    import org.bson.Document;
    import org.bson.types.ObjectId;
    
    MongoClient mongoClient = MongoClients.create(...);
    MongoDatabase db = mongoClient.getDatabase("testDb");
    MongoCollection collection = db.getCollection("testCollection");
    collection.updateOne(
        Filters.and(
                Filters.eq("_id", new ObjectId("43jh4j343j4j")),
                Filters.eq("array._arrayId", new ObjectId("dsd87dsa9d87s9d7"))
        ),
        Updates.combine(
                Updates.set("array.$.someField", "new value 1"),
                Updates.set("array.$.someField2", "new value 2")
        )
    );
    

    This thread has helped me towards the right solution, but I had to do more research for the full solution, so hoping that someone else will benefit from my answer too.

提交回复
热议问题