How to do an update in an array with MongoDB and Morphia?

0

I need to update an Ingredient in the ingredient list. Until then I just know how to update the entire JSON. How do I update only one item in the array?

{
"_id" : ObjectId("573c721f75fe72149c4d9987"),
"className" : "br.com.teste.productdatasheet.dto.Datasheet",
"name" : "Donut",
"size" : "Normal",
"weight" : {
    "value" : 250,
    "unit" : "g"
},
"ingredients" : [ 
    {
        "name" : "Farinha de Trigo",
        "brand" : "Dona Benta",
        "packing" : "Saco",
        "packingAmount" : {
            "value" : 5,
            "unit" : "kg"
        },
        "requiredAmount" : {
            "value" : 450,
            "unit" : "g"
        },
        "price" : 5.89
    }, 
    {
        "name" : "Leite",
        "brand" : "Qualquer",
        "packing" : "Caixa",
        "packingAmount" : {
            "value" : 1,
            "unit" : "l"
        },
        "requiredAmount" : {
            "value" : 500,
            "unit" : "ml"
        },
        "price" : 2.3
    }, 
    {
        "name" : "Açúcar",
        "brand" : "Qualquer",
        "packing" : "Saco",
        "packingAmount" : {
            "value" : 5,
            "unit" : "kg"
        },
        "requiredAmount" : {
            "value" : 300,
            "unit" : "g"
        },
        "price" : 9.8
    }
]
}
    
asked by anonymous 26.05.2016 / 20:33

1 answer

0

After searching I was able to solve:

@Override
public void updateIngredient(Ingredient from, Ingredient to) throws Exception {
    UpdateOperations<Datasheet> ops;
    Query<Datasheet> updateQuery = getDatastore().createQuery(Datasheet.class)
            .field("ingredients.name").equal(from.getName())
            .field("ingredients.brand").equal(from.getBrand())
            .field("ingredients.packing").equal(from.getPacking())
            .field("ingredients.packingAmount").equal(from.getPackingAmount())
            .field("ingredients.price").equal(from.getPrice());
    ops = getDatastore().createUpdateOperations(Datasheet.class).disableValidation()
            .set("ingredients.$.name", to.getName())
            .set("ingredients.$.brand", to.getBrand())
            .set("ingredients.$.packing", to.getPacking())
            .set("ingredients.$.packingAmount", to.getPackingAmount())
            .set("ingredients.$.price", to.getPrice())
            .enableValidation();
    UpdateResults uResult = getDatastore().update(updateQuery, ops);
}//updateIngredient
    
26.05.2016 / 23:26