Reputation: 591
I'm trying to update database information from some information I get from a Thymeleaf powered page. Basically each page is constructed using a single document from MongoDB. Now I'd like to allow some users to change this page, since the actual page is not that complex, I was giving a shot to this JavaScript plugin that would create text area divs and send them to server via Ajax (http://www.dyve.net/jquery/?editable).
Since the document has only unique fields, I can set the field id in the html to the name of the mongodb field, like product-description. I can send the id through and the update is really simple:
public boolean updateValueWithKey(String id, String k, String v) {
Criteria c = Criteria.where(id).is(id);
Query q = new Query().addCriteria(c);
Update u = u.set(k, v);
WriteResult w = operations.updateFirst(q, u, clazz);
return w.wasAcknowledged();
}
Where id is the document id code, k is the field name (key) and v the value.
But I realized that one particular part of the document has an array, but I don't understand how can I update a particular field of an array.
The Update class has a inner class called PushOperatorBuilder with a method called atPosition, which the docs mention that: "Forces values to be added at the given {@literal position}."
But I really don't understand how to use that, any attempt to reach that method from the instantiated Update object just gave me errors.
Help?
Upvotes: 0
Views: 4264
Reputation: 75994
You can try postional operator to locate array field in a query followed by update at that position.
Something like
Criteria c = Criteria.where(id).is(id).and("array.key").is("oldvalue");
Query q = new Query().addCriteria(c);
Update u = new Update().set("array.$.key", "newvalue");
WriteResult w = mongoOperations.updateFirst(q, u, clazz);
Update at specific position
Criteria c = Criteria.where(id).is(id);
Query q = new Query().addCriteria(c);
Update u = new Update().push("arrayname").atPosition(position).each(newvalue);
WriteResult w = mongoOperations.updateFirst(q, u, clazz);
Upvotes: 5