Python: how to find documents with specific fields

I am using python and mongodb. I have a collection containing 40,000 documents. I have a group of coordinates and I need to find which document these coordinates refer to. Now I am doing:

cell_start = citymap.find({"cell_latlng":{"$geoIntersects":{"$geometry":{"type":"Point", "coordinates":orig_coord}}}})

      

This method is a typical geoJSON method and it works well. Now I know that some docs have a field like this:

{'trips_dest':......}

      

The value of this field is irrelevant, so I'll just skip that. The point is, instead of searching for documents from all those 40,000 documents, I can simply search for documents from documents with the "trip_dest" field.

Since I know that only about 40% of the documents have a "trip_dest" field, so I think this will improve efficiency. However, I don't know how to change my code to do this. Any idea?

+3


source to share


1 answer


You need the $ exists query operator. Something like that:

cell_start = citymap.find({"trips_dest": {$exists: true},
                           "cell_latlng":{"$geoIntersects":{"$geometry":{"type":"Point", "coordinates":orig_coord}}}})

      

To quote the documentation:

Syntax: { field: { $exists: <boolean> } }

When <boolean>

true, $exists

matches documents containing this field , including documents where the field value is null



If you need to reject null values ​​use:

 "trips_dest": {$exists: true, $ne: null}

      

As a final note, a sparse index may eventually speed up such a query.

+2


source







All Articles