DEV Community

Cover image for Using MongoDB query syntax to query Relational Database in Java
Muhammad Hewedy
Muhammad Hewedy

Posted on • Updated on

Using MongoDB query syntax to query Relational Database in Java

Spring Data JPA provides a lot of features on top of JPA. Such as Query methods, Query by examples, and a lot more.

It also integrates with JPA Specifications, QueryDSL, Jooq, and other fantastic libraries.

However there’s a specific use-case that exists in most applications which is the need to make the user search by multiple criteria for an entity and its related associations. This is where Spring Data JPA Mongodb Expressions excels.


Spring Data JPA MongoDB Expressions allows you to use MongoDB query syntax to send the queries as JSON string typically from the frontend app to a Rest API and then to the Repository layer.

Here’s an example query that users can send from the frontend:

{
  "lastName": "ibrahim",
  "$and": [
    {
      "birthDate": {"$gt": "1981-01-01"}
    },
    {
      "birthDate": {"$lte": "1985-10-10"}
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

that will be translated to:

... where last_name=? and birth_date>? and birth_date<=?
Enter fullscreen mode Exit fullscreen mode

As you see, it uses the same notation of the initiative and simple-to-use MongoDB query language with features such as ANDing, ORing, and joining entities.


So How to start?

You can follow the README file on the project page at Github, it contains a lot of details.

Happy coding!

Top comments (0)