diff --git a/optimade/server/entry_collections/entry_collections.py b/optimade/server/entry_collections/entry_collections.py index a963ccdd48..fb4d101605 100644 --- a/optimade/server/entry_collections/entry_collections.py +++ b/optimade/server/entry_collections/entry_collections.py @@ -319,9 +319,6 @@ def handle_query_params( for f in self.all_fields } - if "_id" not in cursor_kwargs["projection"]: - cursor_kwargs["projection"]["_id"] = False - if getattr(params, "response_fields", False): response_fields = set(params.response_fields.split(",")) response_fields |= self.resource_mapper.get_required_fields() diff --git a/optimade/server/entry_collections/mongo.py b/optimade/server/entry_collections/mongo.py index 2da6120f94..97587534f1 100644 --- a/optimade/server/entry_collections/mongo.py +++ b/optimade/server/entry_collections/mongo.py @@ -113,11 +113,16 @@ def _run_db_query( """ - results = [] - for doc in self.collection.find(**criteria): - if criteria.get("projection", {}).get("_id"): - doc["_id"] = str(doc["_id"]) - results.append(doc) + # Handle MongoDB ObjectIDs: + # - If they were not requested, then explicitly remove them + # - If they were requested, then cast them to strings in the response + if "_id" not in criteria["projection"]: + criteria["projection"]["_id"] = False + + if criteria.get("projection", {}).get("_id"): + criteria["projection"]["_id"] = {"$toString": "$_id"} + + results = list(self.collection.find(**criteria)) nresults_now = len(results) if not single_entry: