0

I am switching from Postgres to MongoDB in my Spring Boot application. I enjoyed the privilege of being able to query my database using native queries via the @Query annotation:

@Query(value = "SELECT id\n" +
        "FROM ( \n" +
        "SELECT DISTINCT CASE sender WHEN 1 THEN recipient ELSE sender END AS friend_id \n" +
        "FROM friendrequest WHERE 1 IN (recipient, sender) \n" +
"AND friendrequeststatus = 'ACCEPTED' \n" +
        ") f \n" +
        "LEFT JOIN users u\n" +
        "ON f.friend_id = u.id\n" +
        "ORDER BY friend_id \n-- #pageable\n"
        ,nativeQuery = true)
Page<User> getFriends(Pageable pageable);

Presently I am switching to MongoDB, and Inam using the same models. Is it possible to write advanced native queries using the @Query method, or am I constrained to using the Query object:

    user = mongoTemplate.findOne(
  Query.query(Criteria.where("name").is("Jack")), User.class);

I asked this question because I haven't seen any articles on building complex queries with MongoDB and Spring Boot.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Oto-obong Eshiett
  • 1,459
  • 3
  • 18
  • 33
  • 1
    You can't do it in SQL, obviously, but you can certainly write a BSON query string in `@Query`; see e.g. https://stackoverflow.com/a/33017559/3001761. *"I haven't seen any articles"* - how about https://www.baeldung.com/queries-in-spring-data-mongodb – jonrsharpe Dec 18 '18 at 08:27

1 Answers1

0

First You need to understand the difference between RDBMS and NoSQl. You can refer this question.

There is a considerable difference between SQL and NoSQL, when querying. As an example MySQl has select query keyword and MongoDb has find({}) function to do get the same output.

Though earlier versions of MongoDb cant perform aggregations, equivalent to SQL join queries, latest versions(>=3.2) allow this from $lookup. See the Documentation. Also MongoDb aggregations will help for the code given in the question.

With the understand of NoSql and MongoDb, you can use Spring MongoDB with complex queries. Check this answer as a brief workout with Spring and MongoDb.

Sajith Herath
  • 1,002
  • 2
  • 11
  • 24