I am having problems with querying with MongoDB. Whenever I try to find by ID or any other field, I always get zero results back. And I am also having trouble to use the 'like' operator.
What I wanna query is the titles of the books in a case insensitive way. And I know you can do it like this in MongoDB:
{title: {$regex: /^query.*/i}}
And I try to do this with Panache but I can't get it working:
Book.find("title like ?1", "/^" + query + ".*/i");
I see the following line on the console getting printed out: {'title':{'$regex':'/^Harr.*/i'}}
I've also tried it with a Document, but also not success:
Document query = new Document();
query.put("title", "$regex: /^" + query + ".*/i");
Book.find(query);
And I get zero results back.
And here is my Book class:
public class Book extends PanacheMongoEntity {
@NotEmpty
public String title;
@NotEmpty
public String isbn;
@NotEmpty
public String author;
@Min(1)
@NotNull
public BigDecimal price;
}
And here is my BookResource:
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@Path("/books")
public class BookResource {
@GET
public List<Book> get() {
return Book.listAll();
}
@GET
@Path("/{id}")
public Book find(@PathParam("id") String id) {
return (Book) Book.findByIdOptional(id).orElseThrow(() -> new NotFoundException("Book not found"));
}
@GET
@Path("/title/{title}")
public PanacheQuery<PanacheMongoEntityBase> findByTitle(@PathParam("title") String title) {
Document query = new Document();
// query.put("title", new BasicDBObject("$regex", ).append("$options", "i"));
return Optional.ofNullable(Book.find("title like ?1", format("/^%s.*/i", title))).orElseThrow(() -> new NotFoundException("Book not found"));
}
@POST
public void add(@Valid Book book) {
Book.persist(book);
}
@PUT
@Path("/{id}")
public void update(@PathParam("id") String id, @Valid Book book) {
Book result = Book.findById(id);
if (result != null) {
result.author = book.author;
result.isbn = book.isbn;
result.price = book.price;
result.title = book.title;
Book.update(result);
}
}
}
When I do a findAll via curl I get this:
[
{
"id": "5eb9475b8a4314145246cc10",
"author": "J.K. Rowling",
"isbn": "12345678",
"price": 24.95,
"title": "Harry Potter 1"
},
{
"id": "5eb95a758a4314145246cc25",
"isbn": "456",
"price": 0,
"title": "Java for dummies"
},
{
"id": "5eb95b1a8a4314145246cc27",
"author": "steven king",
"isbn": "456",
"price": 10,
"title": "IT"
}
]
And when I try to find a Book by id, I also get zero results:
curl -X GET "http://localhost:8080/books/5eb9475b8a4314145246cc10" -H "accept: application/json"
=> 404 No Books found.
The only operation that seems to work is the POST (persist), the rest of the methods don't return anything.
I have the following setup:
- MongoDB 4.2 running via Docker
- Quarkus 1.4.2
- JDK 11
And here is my application.properties:
quarkus.mongodb.connection-string=mongodb://localhost:27017
quarkus.mongodb.database=books
quarkus.log.category."io.quarkus.mongodb.panache.runtime".level=DEBUG