I'm using MongoDB and Spring 3. I have the following domain object:
@Document(collection = "users")
public class User {
@Id
private String id;
private List<Post> posts;
}
I want to add a Post to a User, but what is the best/most efficient way to do that? I can see a way to do this programmatically - find the user, add a new post object to the list and save the user again - but I don't think this is very elegant or efficient.
From the documentation it seems like I need to use the $push operator but I can't seem to find any examples of how to do this with Spring's MongoTemplate. Can anyone provide an example?
$push would be the correct way to add a new document to the array.
You can see example code in this presentation (slide 22). The relevant line would be:
mongoTemplate.updateFirst(collection,
... new Query(where("_id").is(...)),
... new Update().push("field", dbo));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With