M001: Chapter 4 Lab 1

Why is the following not giving me the correct count [ use sample_training ]

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

while this command gives correct count

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

Thanks

The operator $elemMatch is for array. The field start station location is an object. However, start station location.coordinates is an array.

Thanks, Steve for pointing that out.

Just want to understand the use of $elemMatch.

I changed my query to

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

It returns me 0.

I tried the above query by fully qualifying the element to start station location.coordinates.0 as follows:

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

That does not work either.

Thanks for your attention.

I cannot explain better than the documentation.

See https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ for description and examples.