How to update an array with Mongodb and Morphia?

Asked

Viewed 29 times

0

I need to update a Ingredient in the ingredient list. So far I only know how to update the entire JSON. How do I update only one item of 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
    }
]
}

1 answer

0


After searching I managed 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.