Is the MongoDB $push operator the way to add an embedded document?


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?

share|improve this question

$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));
share|improve this answer
2 
Thanks this helped. I used the following: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 the Update class statically - like i've seen done in many examples - and this did not allow the push method. – chrisjleu Jun 7 '12 at 20:50




출처 - 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/



Posted by linuxism
,