There are people in a city. A city is represented by a mongodb collection called "cities". The people in the city are either alone or walking togheter with another person in the same city.
The schema is:
{
name: String,
people: [
{
name: String,
status?: String,
walkingWith?: String
}
]
}
Fields "status" and "walkingWith" are the ones I would like to use, if my strategy is correct.
Here are some entries:
var newyorkPeople = [];
newyorkPeople[0] = {"name": "Jack", "status": "alone", "walkingWith": "none"};
newyorkPeople[1] = {"name": "James", "status": "meeting", "walkingWith": "Maria"};
newyorkPeople[2] = {"name": "Robert", "status": "meeting", "walkingWith": "Nina"};
newyorkPeople[3] = {"name": "Steven", "status": "alone", "walkingWith": "none"};
newyorkPeople[4] = {"name": "Maria", "status": "meeting", "walkingWith": "James"};
newyorkPeople[5] = {"name": "Nina", "status": "meeting", "walkingWith": "Robert"};
I then enter a new city with people in it:
db.cities.insert({"name": "New York", "people": newyorkPeople});
Now, the goal is to make it easy for a client(frontend) to describe what people there are in this city. And group them. First show all the lone people. And then the "couples" that are walking togheter.
Im not sure if the grouping is better to be done in the backend or in the frontend (angular).
In backend (api) Im using express.js. The api could just return all the city document to the frontend. And then the frontend would be responsible to sort/group the people.
In that case, the strategy Im thinking about would be:
Loop through the people and only print the lone people. Those that are walking with somebody, should go in another array. So the first step, to show all the lone people, is accomplished.
Now, I still need to show couples. First I need to show the couple "James and Maria" and then the couple "Robert and Nina". Should I create an array for each couple? In the example above, it should create 2 arrays.
However, Im not sure this is the best strategy. Im fine in modifying the db-schema or even to let the backend deliver the grouped people if somebody could come with some good suggestion.
You can use the following(simplified of yours) schema
{
name:Stirng, //name of the person
city:String, //name of the city
status:String, //status
walkingWith:String //name of the person walking with
}
The benefit of using this schema is, it can make your queries easier. Let's query your need.
1- all people in a city
db.city.aggregate([
{$group:{_id:"$city", people:{$push:"$name"}}}
])
2- all people in a city alone
db.city.aggregate([
{$match:{status:"alone"}},
{$group:{_id:"$city", people:{$push:"$name"}}}
])
3- all people in a city meeting with someone
db.getCollection('demos').aggregate([
{$match:{status:"meeting"}},
{$group:{_id:"$city", people:{$push:{name:"$name", walkingWith:"$walkingWith"}}}}
])