EzyMongo: Query Data
Updated at 16910327410001. Create a Repsitory
If you have no idea about EzyMongo, please take a look the introduction. And now, let's say we have a `Book` class like this:
@EzyCollection public class Book { @EzyId private Long id; private Long categoryId; private Long authorId; private String name; private BigDecimal price; private LocalDate releaseDate; private LocalDateTime releaseTime; }
To create a repository, you just need add a repository like this:
@EzyRepository public interface BookRepository extends EzyMongoRepository {}
2. Available methods
EzyMongo contains some method:
- save: to save one or many entities
- delete: to delete one or many entities
- find: to entities by id, ids, by field or find all
- count: count all entities
example:
bookRepository.save(book);
bookRepository.delete(bookId);
Book book = bookRepository.findById(bookId);
bookRepository.count()
For a completed example, you can look at here.
3. Custom method
EzyMongo supports you create a custom method to query mongodb. Let's say, we want to find a book by name and authorId, we can do like this:
Book findByNameAndAuthorId(String name, Long authorId);
In this method,
name is Book's name` field and `authorId` is `Book's authorId field. It means you can use this template to create a lot of query methods, like:List<Book> findByCategoryIdOrAuthorId(long category, long authorId); List<Book> findByCategoryIdAndName(long category, long authorId, Next next); int countByAuthorId(long authorId);
4. Custom query method
If you have a complicated query and can not create a custom method, you can annotate your method with
@EzyQuery annotation like this:@EzyQuery("{$query: {_id : 4}, $update: {$set: {category: ?0}}}") void updateCategory(String category); // need to have "update" prefix. @EzyQuery("{$query:{name:{$lt:?0}}, $orderby:{name:1}}") List<Book> findByNameLt(String name, Next next); @EzyQuery("{$query:{name:{$gt:?0}}, $orderby:{name:1}}") List<Book> findByNameGt(String name, Next next); @EzyQuery("[{ $group: { _id : 'sum', sum : { $sum: {$toDecimal: '$price'}} } }]") SumBookPriceResult sumPrice(); @EzyQuery("{authorId:{$gt:?0}}") int countByAuthorIdGt(long authorId); // need to have "count" prefix. @EzyQuery("{authorId:{$gt:?0}}") void deleteByAuthorIdGt(long authorId); // need to have "delete" prefix.
4. Pagination
EzyMongo use
Next class to help you specific skip and limit value, you can create Next by:
Next.fromSkipLimit(skip, limit)
// or
Next.fromPageSize(page, size)
Full source code of examples is available on Github
Next
You can take a look how to use custom query result