简体   繁体   中英

Spring Data mongodb view

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 cityCountryhttps://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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM