Robert Sparks
Robert Sparks

Reputation: 11

MongoDB referencing parameter value

I have a small mongo DB and I am trying to write code that will reverence the value of parameters (keys) imbedded in a document.

I have a mongo DB server on localhost and am able to successfully input the json format data structure into my DB. However, when I try to reference the values of this data within, I get the errors as shown.

import pymongo
import json
import time
from datetime import datetime

server = pymongo.MongoClient('localhost')
database = server['testData']
collection = database['testCollection']

test_entry1 = '{"Level1" : {"level2_1" : {"param1" : "1.6","param2" : "32.3","param3" : "11.0"}, "level2_2" : {"param1" : "2.6","param2" : "9.3","param3" : "112.0"}}}'

mongo_import = json.loads(test_entry1)
collection.insert_one(mongo_import)

The above works fine and when I query the database I get the following response (as expected):

{ "_id" : ObjectId("5d0081e931775cbc28cf7704"), "Level1" : { "level2_1" : { "param1" : "1.6", "param2" : "32.3", "param3" : "11.0" }, "level2_2" : { "param1" : "2.6", "param2" : "9.3", "param3" : "112.0" } } }

Now, I would like to reference the data in these parameters. I would like to get a response for all of what is in "level 2_1". The attempt #I made is below...and the error received is below that.

level_1_param_1 = collection.find("level1" : "level2_1")

error:

File "Desktop/Scripts/StackOverflowSnippit.py", line 29, in <module>
    level_1_param_1 = collection.find('"level1" : "level2_1"')
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/collection.py", line 1456, in find
    return Cursor(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/cursor.py", line 146, in __init__
    validate_is_mapping("filter", spec)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/common.py", line 452, in validate_is_mapping
    "collections.Mapping" % (option,))
TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping 

I would also like to be able to get the value of a parameter that is one layer lower like "level1 --> level2_1 --> param2" for instance but so far have been unable to do so.

My hope is to be able to reference the data in this structure as needed.

Upvotes: 1

Views: 348

Answers (1)

Jboulery
Jboulery

Reputation: 288

Your filter should have brackets:

level_1_param_1 = collection.find({"level1": "level2_1"})

Upvotes: 2

Related Questions