0 Daumen
212 Aufrufe

Ich habe eine JSON-Datei, die ich in MangoDB hostelen. Ich möchte einige ihrer Elemente erhalten.

Hier ist die Datei:

{
"_id": "5de9483c65222ef002ad6135",
"election": "local-min-2015",
"type": "FeatureCollection",
"features": [
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [
            5039258.279933322,
            5142586.1579948
          ],
          [
            5039615.847231327,
            5142411.105566747
          ]
        ]
      ]
    },
    "properties": {
      "1": {
        "Partido Popular": "50.64"
      },
      "2": {
        "Partido Socialista Obrero Espanol": "3.22"
      },
      "3": {
        "Unidos Podemos": "1.29"
      },
      "4": {
        "Ciudadanos": "26.18"
      },
      "5": {
        "Vox": "18.45"
      },
      "id": 96918,
      "parent_id": 96916,
      "common_id": "11.01",
      "common_name": "11.01",
      "has_children": true,
      "shape_type_id": 5,
      "shape_type_name": "Majoritarian District",
      "value": "No Data",
      "color": null,
      "title_location": "Majoritarian District: 11.01",
      "Total Voter Turnout (%)": 55.08
    }
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [
            5039258.279933322,
            5142586.1579948
          ],
          [
            5039615.847231327,
            5142411.105566747
          ]
        ]
      ]
    },
    "properties": {
      "1": {
        "Partido Popular": "45.64"
      },
      "2": {
        "Partido Socialista Obrero Espanol": "7.22"
      },
      "3": {
        "Unidos Podemos": "2.29"
      },
      "4": {
        "Ciudadanos": "26.18"
      },
      "5": {
        "Vox": "18.45"
      },
      "id": 96919,
      "parent_id": 96916,
      "common_id": "11.01",
      "common_name": "11.01",
      "has_children": true,
      "shape_type_id": 5,
      "shape_type_name": "Majoritarian District",
      "value": "No Data",
      "color": null,
      "title_location": "Majoritarian District: 11.01",
      "Total Voter Turnout (%)": 55.08
    }
  }
 ]
}


Ich hätte gerne diese

{
"0": {
  "parties": [
    {
      "Partido Popular": 50.64
    },
    {
      "Partido Socialista Obrero Espanol": 3.22
    },
    {
      "Unidos Podemos": 1.29
    },
    {
      "Ciudadanos": 26.18
    },
    {
      "Vox": 18.45
    }
  ],
  "id": 96918
},
"1": {
  "parties": [
    {
      "Partido Popular": 45.64
    },
    {
      "Partido Socialista Obrero Espanol": 7.22
    },
    {
      "Unidos Podemos": 2.29
    },
    {
      "Ciudadanos": 26.18
    },
    {
      "Vox": 18.45
    }
  ],
  "id": 96919
}
}

Bis heute habe ich versucht, die Immobilien zu bekommen, aber ich habe ein Problem:


import pymongo
from bson.son import SON
import json

import os

client = pymongo.MongoClient("mongodb://localhost:27017/")

db = client["Richmond"]

collection = db['Collection']

# select the documents where the field features contains the field 0
cursor = db.collection.find(
  {"_id": "5de9483c65222ef002ad613"},
  { "features": 1, "type": 0, "election": 0, "_id": 0 }
)

for doc in cursor:
  print(doc)


Die cmd gibt mich zuruck:

(base) C:\Users\antoi\Documents\Programming\Richmond\Mongo>python query_mongdb.py
Traceback (most recent call last):
File "query_mongdb.py", line 20, in <module>
  for doc in cursor:
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\cursor.py", line 1156, in next
  if len(self.__data) or self._refresh():
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\cursor.py", line 1073, in _refresh
  self.__send_message(q)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\cursor.py", line 955, in __send_message
  address=self.__address)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1347, in _run_operation_with_response
  exhaust=exhaust)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1465, in _retryable_read
  return func(session, server, sock_info, slave_ok)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1341, in _cmd
  unpack_res)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\server.py", line 136, in run_operation_with_response
  _check_command_response(first)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymongo\helpers.py", line 159, in _check_command_response
  raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Projection cannot have a mix of inclusion and exclusion.
Avatar von

1 Antwort

0 Daumen

Antwort mit KI erzeugt

Wie kann man eine auf MongoDB gehostete JSON-Datei mit Python anzeigen und filtern?

Um aus einer MongoDB-Collection spezifische Daten zu filtern und diese im gewünschten Format anzuzeigen, müssen Sie mehrere Schritte durchlaufen. Nachfolgend wird gezeigt, wie Sie vorgehen können, unter Berücksichtigung des von Ihnen bereitgestellten JSON-Dokuments.

Verbindung zu MongoDB herstellen und Daten abfragen:

1. MongoDB-Datenbank und Collection auswählen:
Zuerst müssen Sie eine Verbindung zu Ihrer MongoDB herstellen und die entsprechende Datenbank und Collection auswählen. Dies haben Sie bereits getan, aber vergewissern Sie sich, dass der Collection-Name korrekt ist.

2. Fehlerbehebung bei Ihrer Abfrage:
Das Problem in Ihrem Skript liegt darin, dass Sie versuchen, gewisse Felder einzuschließen und andere auszuschließen, was in einer Abfrage nicht zulässig ist, außer für das Feld _id, das ausgeschlossen werden kann, auch wenn andere Felder eingeschlossen werden.

Transformation der Daten:

Nachdem Sie die Daten abgefragt haben, müssen Sie die gewünschten Informationen extrahieren und umformen. Dies kann mithilfe eines Python-Skripts erfolgen.

Python-Skript zur Datenextraktion und -umformung:

1. Daten aus MongoDB abrufen:
python
   collection = db['CollectionName']  # Stellen Sie sicher, dass der Collection-Name korrekt ist
   cursor = collection.find({_id: "5de9483c65222ef002ad6135"}, {"_id": 0, "features.properties": 1})
   


2. Die Daten umwandeln, um die gewünschte Struktur zu erhalten:
python
   import json

   def transform_data(doc):
       result = {}
       for idx, feature in enumerate(doc['features']):
           parties = [{'Partido Popular': float(feature['properties']['1']['Partido Popular'])},
                      {'Partido Socialista Obrero Espanol': float(feature['properties']['2']['Partido Socialista Obrero Espanol'])},
                      {'Unidos Podemos': float(feature['properties']['3']['Unidos Podemos'])},
                      {'Ciudadanos': float(feature['properties']['4']['Ciudadanos'])},
                      {'Vox': float(feature['properties']['5']['Vox'])}]
           result[str(idx)] = {
               'parties': parties,
               'id': feature['properties']['id']
           }
       return result

   for doc in cursor:
       transformed_data = transform_data(doc)
       print(json.dumps(transformed_data, indent=2))
   


Erklärung:
- Cursor Abfrage: Das Feld features.properties wird von Dokumenten abgefragt, die die angegebene _id aufweisen. Die restlichen Felder, die nicht benötigt werden (wie type, election), werden nicht ausgeschlossen, um das Problem zu umgehen, das sich aus der Mischung von Ein- und Ausschlüssen ergibt.
- Daten Transformation: Die Funktion transform_data durchläuft jedes Feature in den abgerufenen Dokumenten und extrahiert die für die Parteien spezifischen Daten. Anschließend wird es in das gewünschte Ausgabeformat umgewandelt.

Beachten Sie, dass der Collection-Name im Skript durch Ihren tatsächlichen Namen ersetzt werden muss ('CollectionName'). Außerdem sollte die _id entsprechend dem Dokument angepasst werden, das Sie abfragen möchten.

Dieses umgestaltete Skript hilft dabei, die Daten aus Ihrer MongoDB-Datenbank zu extrahieren und in das geforderte Format umzuwandeln, sodass Sie die gewünschten Informationen effizient anzeigen können.
Avatar von

Ein anderes Problem?

Stell deine Frage

Willkommen bei der Stacklounge! Stell deine Frage einfach und kostenlos

x
Made by a lovely community