Reputation: 4307
Since mongo is a nosql database I'm a bit confused how to represent model of data in java corresponding to mongo collections/documents.
I have a person form with one field, Country
and second City
. When I choose country, the list of cities from particular country fills dropdown list. In typical SQL relation it would be one-to-many relation.
I read about possibilities how to store it in mongo - I can do it with emebedded documents, so a Country
object with List<String>
of city names:
{
_id: "PL",
name: "Poland",
cities: [
{
city: "Lodz",
state: "LDZ",
zip: "XX-XXX"
},
{
city: "Warsaw",
state: "MZK",
zip: "XX-XXX"
}
]
}
However it doesn't make sense that each time I fetch person from DB I'd fetch also whole country with all cities. So the only possibility of doing it is by creating two separate collections ( Cities, Countries ) and create DBRef, then create two fields in Person
model one for city and one for country, but how would these two particular classes look like ? Should city have country ID ? Is it appropriate way of thinking or I'm going in wrong direction ? Can someone provide me an example of mongo JSON and java class ?
Upvotes: 2
Views: 2733
Reputation: 3250
Your approach seems ok. In my opinion, in this case you should be free use it without dbrefs. Because Mongo is a document based nosql db so embedded documents are the way store data mostly.
While you are fetching country, you don't need to fetch all cities under the country.
Simple example: db.country.find( { name: "Poland" }, {name: 1, id: 1 } )
Returns only name and id fields.
City may have has own id. Person model may have city(may be all stuff about it) and country(you may save only id and name field) fields as you told.
Countries(added only extra city id):
{
_id: "PL",
name: "Poland",
cities: [
{
_id: "1",
city: "Lodz",
state: "LDZ",
zip: "XX-XXX"
},
{
_id: "2",
city: "Warsaw",
state: "MZK",
zip: "XX-XXX"
}
]
}
Person:
{
_id: "1",
name: "John",
surname: "Doe",
country: {_id:"PL",name="Poland"}, // I think you can save without citylist, country object
city: {
_id: "2",
city: "Warsaw",
state: "MZK",
zip: "XX-XXX"
}
My answer is just an opinion in this case(Your request about java class , it shows differences with some frameworks, Also you can think these documents as pojo).
Upvotes: 5