Chapter 4 : Advanced CRUD Operations Lab 1: Querying Arrays and Sub-Documents

Hello everyone, hope you are doing well.

I have been trying to solve a query regarding finding the trips in the sample_training.trips collection started at stations that are to the west of the -74 latitude coordinate?

And I have been trying the below query to find the solution :
db.trips.find({“start station location.coordinates” : {"$regex" : /74./}})

but I am not getting any kind of output or error! Can someone please help me?

The field start station location.coordinates is an array of 2 elements. One of them is the latitude and the other is the longitude. Both are numbers. Even if $regex could be applied to numbers you would missed all -73.xxxx or all -75.xxxx numbers depending which means being at the west.

Okay, I understood. But whenever I tried to find the exact latitude value, I was able to. So how do I find all the coordinates starting with -74/74? i tried using the $options : s too. I still don’t get any output.

You may use any of the comparison operators; $gt, $lt, $gte, $lte. Some examples given at https://docs.mongodb.com/manual/reference/operator/query/gt/

The operator $trunc might works to remove the decimals.

1 Like

thankyou so much for the help, I will try it!

1 Like

Just for ease of completing the question, it would be useful if the question stated which element of the array was latitude.

I appreciate you can look up which comes first in standard latitude and longitude notation, but really is it necessary for the course?

Element 0 btw.

Extra note: Since it is element 0, then the Detailed answer should have .0 at the end of coordinates e.g. coordinates.0

I do wonder if there is a better set of data available to demonstrate this particular aspect of dot notation.

db.trips.findOne({“start station location.coordinates”:{"$regex":-74}})
not geting answer can u help me here ?

The $regex operator is for strings. Coordinates are numbers.

I tried but not unable to get answer.

What did you tried?

BTW It should read, “west of the -74 longitude”. Latitude maps north to south and Longitude maps east to west.

The standard is LAT-LONG.

Good point, when trying to get a document for a coordinate Y = -74.015756 i got a null (coordinates.1). In this case i think the 0 at the end is needed.

When coordinates.0 equals to -74.015756 i got valid documents.

it’s taking me quite sometime and give me the right answer for this question.
db.trips.find( {"$and":[{“start station location.coordinates.0”:{"$lte":-74}}, {“start station location.coordinates.0”:{"$gt":-75}}] } ).count()

Thank you. I was searching for the same.

db.trips.find({ “start station location.coordinates.0”: { “$lt”: -74 }}).count()