1

We use Spring Data mongodb version 2.1.3.

We have two collections cities and countries.

@Document
public class City {
    private String name;
    private ObjectId id;
    private ObjectId countryId;
}
@Document
public class Country {
    private String name;
    private ObjectId id;
}

We have db repositories extending org.springframework.data.mongodb.repository.MongoRepository.

Now we want to make REST API end-points which would return aggregated data CityCountryDto. For this reason we want to make read-only view cityCountry https://docs.mongodb.com/manual/reference/method/db.createView/

db.createView (
   "cityCountry",
   "city",
   [
     { $lookup: { from: "country", localField: "countryId", foreignField: "id", as: "country_docs" } },
     { $project: { "country_docs._id": 0} }
   ]
)

We tried

@Document
CityCountry extends City {

    private Country country;
}

Note, in order it to work, we had either to create the view before we run the application in the database or we had to use data change log tool (like Flyway or liquibase or mongobee). To make things easier, consider that the view existed in the database before we start the application.

My question, is there Spring data support view out of box? Is there a better way to achieve this?

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114

1 Answers1

-1

Yes, there are some repositories like JpaRepository for MongoDB. First you need to get the mongo driver and set some properties for your connection in application.properties from your spring boot application :

1. spring.data.mongodb.username= [your username] 2. spring.data.mongodb.password= [your password] 3. spring.data.mongodb.database= [your database] 4. spring.data.mongodb.port=27017 5. spring.data.mongodb.host=localhost

I've left intentionally the port and host because by default the MongoDB server opens on the 27017 port and localhost host.

After this, you can create some repositories by extending the MongoRepository<MODEL,ID> like here

user1234SI.
  • 1,812
  • 1
  • 8
  • 22
  • OK, but the application is already connected to the database. My question is about Spring Data monogo db view features. If it is available out of box instead of writing code myself? – Yan Khonski Jan 17 '20 at 10:34
  • @YanKhonski did you find any answer for this problem please? – sabri mahmoud Mar 25 '22 at 14:08
  • https://stackoverflow.com/questions/64882182/spring-data-with-mongodb-views it was some time ago, so I do not remember things well. I think we gave up on using the views. – Yan Khonski Mar 25 '22 at 20:45