I think this is a fairly basic question, but I can't figure this part out. So, basically, in my code, I have isolated a document, like so:
document = collection.find_one(name)
And now that I have this document, I want to know how to print out a certain key for this specific document. So, basically, this document looks like this right now:
{
"_id" : ObjectID("...")
"name": ABCD
"info": {
"description" : "XYZ"
"type" : "QPR"
}}
And I want to know how I can extract and print "XYZ" using the variable "document" that has the entire document in it.
document is a regular Python dictionary:
print(document["info"]["description"])
This, as well as, a lot of relevant PyMongo basic usage information is covered in the PyMongo Tutorial - make sure to study it.
It is just a dictionary
print(document['info']['description'])
or if you are not sure if your document contains the right keys
info = document.get('info', None)
if info:
print(document.get('description', 'No description'))
Related
in my database, there are two companies with same name.
[
{
"name": "samsung",
"store_code": "34d"
},
{
"name": "lg",
"store_code": "333"
},
{
"name": "lg",
"store_code": "3511"
}
]
like this..
my question is, I juse made my python function to get store information by name.
that looks like this..
async def fetch_store_by_name(store_name):
document = collection.find_one({"name":store_name})
return document
and I can only get the first lg company's information.
how can I get both informations of lg company from my mongodb?
Use find instead of find_one .
https://www.w3schools.com/python/python_mongodb_find.asp
I assumed you're using pymongo, just change find_one to find method. Like this:
async def fetch_store_by_name(store_name):
document = collection.find({"name":store_name})
return document
Here some documentation : https://pymongo.readthedocs.io/en/stable/tutorial.html#querying-for-more-than-one-document
You can use collection.find({"name":store_name})
Reference:
https://www.w3schools.com/python/python_mongodb_find.asp
Using variables such as name, address, zip code to identify a document is not a good approach as there may be the same names, names with different cases, spaces ex: LG, lg.
You can use the default mongo _id as a unique property to find the doc. Still you want to get the document then use collection.find({"name":store_name}) it will returns multiple documents ab array. If you want to retrieve only one doc then use collection.findOne({"name":store_name})
query = {
"is_deleted" : False,
"status_value" : "PROSES"
}
if keyword != "":
query["$text"] = { "$search" : keyword }
db.db_konten.find(query)
I have a pymongo query using the text search of MongoDB. It works fine. But I found out that it cant searh the word very ? Is there a reason why. Im using python3 and Flask
When your text index is set to English, it will exclude certain stop words, including very.
If you're interested, the full list is in the MongoDB source code.
You can also override it by setting the $language parameter when creating the text index.
All i am a bit new to python and more so have background in other languages. My specific question is what is the easiest way to get to location within a dictionary or json document by using multiple properties of each doc entry.
Example doc structure:
[
{"Car" : "Ford", "Color" : "Red", "ID" : 1},
{"Car" : "Ford", "Color" : "Blue", "ID" : 2},
]
Is there an easy way to say search for a Red Ford using something other than having to write a iteration function unique to each doc to locate those records?
print (doc["Ford"]["Red"])
or something similar to how a SQL works in a database like
Select * from doc where Car='Ford' and Color='Red'
Just starting down the python path with multiple document structures and want to make sure i'm not doing something more crudely than it needs to be. I know the iteration will of course work but you have to kinda code one for each document and it just seems like there would be something simpler but not sure.
Thanks!
Tim
You could utilize an array filter based on your current example:
[o for o in doc if o["Car"] == "Ford" and o["Color"] == "Red"]
Alternatively, filter:
list(filter(lambda x: x["Car"] == "Ford" and x["Color"] == "Red", doc))
I am working on a system to output a JSON file and I use Python to parse the data and display it in a UI (PySide). I now would like to add filtering to that system and I think instead of writing a query system, if there was one out there for JSON (in Python), that would save me a lot of development time. I found this thread:
Is there a query language for JSON?
but that's more for a Web-based system. Any ideas on a Python equivalent?
EDIT [for clarity]:
The format the data that I'll be generating is like this:
{
"Operations": [
{
"OpID": "0",
"type": "callback",
"stringTag1": "foo1",
"stringTag2": "FooMsg",
"Children": [...],
"value": "0.000694053"
},
{
"OpID": "1",
"type": "callback",
"stringTag1": "moo1",
"string2": "MooMsg",
"Children": [...],
"value": "0.000468427"
}
}
Where 'Children' could be nested arrays of the same thing (other operations). The system will be built to allow users to add their own tags as well to the data. My hope was to have a querying system that would allow users to define their own 'filters' as well, hence the question about the querying language. If there was something that would let me do something like "SELECT * WHERE "type" == "callback" and get the requisite operations back, that would be great.
The suggestion of Pync is interesting, I'll give that a look.
I notice this question was asked a few years ago but if someone else find this, here are some newer projects trying to address this same problem:
ObjectPath (for Python and Javascript): http://objectpath.org/
jsonpath (Python reimplementation of the Javascript equivalent): https://pypi.org/project/jsonpath/
yaql: https://yaql.readthedocs.io/en/latest/readme.html
pyjq (Python bindings for jq https://stedolan.github.io/jq/): https://pypi.org/project/pyjq/
JMESPath: https://github.com/jmespath/jmespath.py
I personally went with pyjq because I use jq all the time for data exploration but ObjectPath seems very attractive and not limited to json.
I thought about this a little bit, and I lean towards something less specific such as a "JSON Query Language" and considered something more generic. I remembered from working with C# a bit that they had a somewhat generic querying system called LINQ for handling these sort of querying issues.
It looks as though Python has something similar called Pynq which supports basic querying such as:
filtered_collection = From(some_collection).where("item.property > 10").select_many()
It even appears to have some basic aggregation functions. While not being specific to JSON, I think it's a least a good starting point for querying.
You can also check out PythonQL, a query language extension to Python that handles SQL and JSON queries: pythonql
pyjsonq
https://github.com/s1s1ty/py-jsonq
from pyjsonq import JsonQ
qe = JsonQ('myfile.json')
res = qe.at('products').where('cat', '=', 2).get()
print(res)
"""
[
{
id: 3,
city: 'dhk',
name: 'Redmi 3S Prime',
cat: 2,
price: 12000
},
...
]
I think it's important that the interaction with json is in-memory so that you can still do things manually for complex criteria
I'm using freebase library to print the article. All is working fine. But I want to ask something from you. Following example working fine. Suppose I have title like this bol (film). Now I want to use this title like this "id": "/en/bol_(film)",. But This is not working. In wikipedia API, We can use this title as bol20%28%film29%. Can any one help me? thanks so much
query = [{
"id": "/en/barak_obama",
"/common/topic/article": [{
"id": None
}],
"/common/topic/image": [{
"id": None
}]
}]
EDIT : I have read this for freebase site. But This is not working.
For example, $0028 in a fully-qualified name represents a left parenthesis and $0029 represents a right parenthesis. (See Section 2.5.9 for the full list of legal characters in fully-qualified names.
There is no guarantee that there will be an id /en/foo for a given title "Foo". In order to find the correct id for your topic you have to either use the search service to get a list of candidate ids, or use MQL for exact phrase matches.
Search
https://www.googleapis.com/freebase/v1-sandbox/search?query=bol
or
http://tinyurl.com/3w9yvyz