Hello I want to get a specific key via TinyDB but I am only getting an empty result.
Here is a simple example of my db:
{"_default": {
"1": {
"1082685467876675736": "https://stackoverflow.com/"
}
}}
Here I am trying to get the url for a specific pid (https://stackoverflow.com/ in this case):
db = TinyDB('db.json')
pid = 1082685467876675736
url= db.get(Query()[str(pid)])
print(url)
This returns an empty result. Please note: I never know the url. All I have for a query is the pid.
I would appreciate any help :)
What you trying to accomplish is to find an entry by a key name. But queries in databases were mostly build to find values on specific keys.
I see two options for your situation:
1. Redesign your database schema
If the pid is an important value for you to query for, don't store it as a key - store it as a value instead; like this:
Then you can easily query this document with:
2. Use the
exists()queryAs of the nature of NoSQL databases not every document has look the same. You are free to add or remove keys now and then from some of your documents. That said there may be a need of selecting a subset of document which have (or not have) a specific key.
As an example think of a database with blog posts. Some of them have comments (so the documents got the list of comments under the key
comments). If you are interested in Posts with comments you could query them regardless of the content of thecommentskey (which is very useful).In your example this one
pidmay not devide your data into groups. It is value which is diffrent and present on every document I guess. Soexists()is not intended and far from best practice here.However, this should work anyway: