0

Below is a collection in mongodb. I need to return the bus_number given a start stop and an end stop. the constraint is that that the index of the end stop has to be greater than the index of the start stop. So, given start=226 & end=229 the returned value should be 1A. start=229 & end=226 should return nothing.

{
"_id" : ObjectId("59be068"),
"route" : "1A",
"route_patterns" : [
    {
        "route_pattern_id" : "00010001",
        "route_stops" : [
            {
                "stop_id" : "226",

            },
            {
                "stop_id" : "228"
            },
            {
                "stop_id" : "229"
            },
            {
                "stop_id" : "227"
            }
        ]
    }
]}

Edit: my structure now looks like this: {
"route":"1A", "route_pattern_id":"00010001", "route_stops":[
{
"stop_id":"226", "stop_number":0 }, {
"stop_id":"228", "stop_number":1 }, {
"stop_id":"229", "stop_number":2 }, {
"stop_id":"227", "stop_number":3 } ] }

This way I am now using the stop_number. Not a clean solution.

This is what I have done:

entity_start = db.routes.find({
    "route_patterns.route_stops.stop_id": str(start_stop)
})
dumps(entity_start)
start_buses = [routes['route'] for routes in entity_start]
entity_end = db.routes.find({
    "route_patterns.route_stops.stop_id": str(end_stop)
})
end_buses = [routes['route'] for routes in entity_end]

set_two = set(start_buses)
set_one = set(end_buses)

return dumps(set_one.intersection(set_two))
  • Do not convert *stringify* the inputs values. Instead, I suggested that you fix your document and use the appropriate type for "stop_id" which should be integer. That being said, a regular `find()` query will not help in your case. You will need to use the `aggregate()` method. – styvane Jul 20 '17 at 05:06
  • Thanks. I changed the structure of the document and removed the stringify. basically removed route_patterns and everything then got to be only one level deep. – 1__elephant__1 Jul 20 '17 at 13:43
  • I can't see the changes you made. Please use the [edit link](https://stackoverflow.com/posts/45147403/edit) on your question to show to show us your document structure. – styvane Jul 21 '17 at 09:22

0 Answers0