Framework & Platform/Spring
spring data - mongoTemplate embedded document insert
linuxism
2013. 7. 13. 18:24
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));
| answered Jun 6 '12 at 6:18 |
|
| |
출처 - http://stackoverflow.com/questions/10905508/is-the-mongodb-push-operator-the-way-to-add-an-embedded-document
this presentation slide 22에서 mongoTemplate.getConverter().write()는 생략해도 된다.
중요한건 push()이다. --> http://docs.mongodb.org/manual/reference/operator/push/
mongoTemplate.updateFirst(Query.query(Criteria.where("username").is("username_1")), new Update().push("posts", newPostObject), User.class);
I think I got a bit confused because I was trying to user theUpdate
class statically - like i've seen done in many examples - and this did not allow thepush
method. – chrisjleu Jun 7 '12 at 20:50