Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
chrisjleu Avatar asked Oct 23 '25 17:10

chrisjleu


1 Answers

$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));
like image 142
Asya Kamsky Avatar answered Oct 26 '25 10:10

Asya Kamsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!