3

I am trying to implement a bus route listing application. My goal is to list buses that passes through two user given points(locations).

I am using mongodb in the backend. A simple structure of the data is like:

....
{ name: 'Bus-N', route: ["Loc1", "Loc2", "Loc3", "Loc4", "Loc5" ], startTime:'..'},
{ name: 'Bus-M', route: ["Loc2", "Loc3", "Loc4"], startTime:'..'}
....

Assumption: I have the list of all buses and for each bus I have all of it's travel routes.

User gives his start location and his destination as input.

  1. How can I use these inputs(start location and destination) to query across this database to list all the buses passing by the two points? For example: If the input is (Loc3, Loc4) I need the output as (Bus-N, Bus-M).
  2. If there is a better way to implement this(which obviously there should be), please recommend the required changes.

I am new to mongodb. Please help with this, thanks in advance.

1
  • $all is what you're looking for: link. Tested it too..it works. db.collection.find({ route: { $all: ["Loc3", "Loc4"] } }). Commented Sep 8, 2019 at 12:00

1 Answer 1

4

You need to use array query operators like:

  1. $elemMatch
  2. $and

during your .find or .findOne query. You could find more info about it in the official MongoDB documentation, (syntax for mongoose is just the same)

You also could find useful information for your case in this question which explains the difference between $all and $in operators for array fields.

Your query should be looked like this:

Model.find({ route: { $in: ["start_point", "dest_point"] } }).exec(callback)

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a better solution to this problem? Is this method gong to work well if I have a few thousand entries?
@Joseph, the only was to improve performance on large-scale collections in using index on necessary fields. I am just answering another question on SW about it, so you could check it here: stackoverflow.com/questions/57841749/… and other links in that question. I guess you'll find it very helpful in your case, esp if you need to build out huge and complicated queries via aggregation. But the only problem that I don't know how much index increases mongo performance on array type fields.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.