My document is
{
_id: 1,
age: "young",
hobby: [
{
vehicle: "car",
velocity: "fast"
},
{
vehicle: "motorcycle",
velocity: "fast"
}
]
}
My goal is: when age became old, first hobby became "slow" but others remain "fast"
My code is:
mongoTemplate.updateFirst(
Query.query(where("_id").is("1")),
Update.update("age", "old")
.set("hobby.$[elem].velocity", "slow")
.filterArray(Criteria.where("elem").is(0)), "collection name")
But it does not work, result is:
{
_id: 1,
age: "old",
hobby: [
{
vehicle: "car",
velocity: "fast" <<--- not slow
},
{
vehicle: "motorcycle",
velocity: "fast"
}
]
}
I could achieve my goal with
mongoTemplate.updateFirst(
Query.query(where("_id").is("1111")),
Update.update("age", "old")
.set("hobby.$[elem].velocity", "slow")
.filterArray(Criteria.where("elem.vehicle").is("car")), "collection name")
But I want modify FIRST array element, not car array element
>Solution :
If you always only want to update the first element, then you can refer to the first element with 0. The standard query would be:
db.collection.update({ _id: 1111 },
{
$set: {
"age": "old",
"hobby.0.velocity": "slow" // note the '0'
}
})
I don’t know spring but I presume the query would be something like:
mongoTemplate.updateFirst(
Query.query(where("_id").is("1111")),
Update.update("age", "old")
.set("hobby.0.velocity", "slow") // note the '0'