Firestore - How to get data from an array field in python - python

I'm having a problem on how I will get the data/value from the field which is an array. Please see image:
In the image, I want to get the data/value of parking_code which is from the array field (parkings).
I tried this one:
parking2 = db.collection(u'parking').document().get({u'parkings.parking_code'})
but it returns me like this: <google.cloud.firestore_v1.document.DocumentSnapshot object at 0x0000014925256550>
I also tried this kind of code:
parking2 = db.collection(u'parking').document().get({u'parkings.parking_code'}).to_dict()
but it returns a None value. Anyone who has solution on this or at least just an idea, please I need your help.

According to the official documentation:
A DocumentSnapshot contains data read from a document in your Cloud
Firestore database. The data can be extracted with the getData() or
get(String) methods.
If the DocumentSnapshot points to a non-existing document, getData()
and its corresponding methods will return null. You can always
explicitly check for a document's existence by calling exists().

doc_ref = db.collection(u'parking').document(u'D7k...')
doc = doc_ref.get()
print(doc.to_dict())
https://cloud.google.com/firestore/docs/query-data/get-data#custom_objects

Related

How to get Document Name from DocumentReference in Firestore Python

I have a document reference that I am retreiving from a query on my Firestore database. I want to use the DocumentReference as a query parameter for another query. However, when I do that, it says
TypeError: sequence item 1: expected str instance, DocumentReference found
This makes sense, because I am trying to pass a DocumentReference in my update statement:
db.collection("Teams").document(team).update("Dictionary here") # team is a DocumentReference
Is there a way to get the document name from a DocumentReference? Now before you mark this as duplicate: I tried looking at the docs here, and the question here, although the docs were so confusing and the question had no answer.
Any help is appreciated, Thank You in advance!
Yes,split the .refPath. The document "name" is always the last element after the split; something like lodash _.last() can work, or any other technique that identifies the last element in the array.
Note, btw, the refPath is the full path to the document. This is extremely useful (as in: I use it a lot) when you find documents via collectionGroup() - it allows you to parse to find parent document(s)/collection(s) a particular document came from.
Also note: there is a pseudo-field __name__ available. (really an alias of documentID()). In spite of it's name(s), it returns the FULL PATH (i.e. refPath) to the document NOT the documentID by itself.
I think I figured out - by doing team.path.split("/")[1] I could get the document name. Although this might not work for all firestore databases (like subcollections) so if anyone has a better solution, please go ahead. Thanks!

Is there a way in firestore to get full document path for documents retrieved using collection_group query in python?

For example, I have a subcollection called schedule whose path is "/organization/{organization_doc}/team/{team_doc}/schedule/{schedule_doc}" and my collection group query is
db
.collection_group(u'schedule')
.where(u'active', u'==', True)
.where(u'send', u'==', True)
.stream()
I need to the get the document path for the documents retrieved using this query (ex:/organization/1UlA6MneaEnJO5BvTTtO/team/pcmR21Rc0ZdpacsY1tuC/schedule/mxDROVShx3Uo3FMN9Ohr).
I'm am able to get schedule_doc id(mxDROVShx3Uo3FMN9Ohr) using doc.id but I need the complete path which includes organization_doc id and team_doc id.
When you're iterating the results of the stream, each DocumentSnapshot object will have a reference property which is a DocumentReference object that contains the full path of the document.
Sure there is, but it's not well documented.
docs = db.collection_group(u'schedule')\
.where(u'active', u'==', True)\
.where(u'send', u'==', True)\
.stream()
for doc in docs:
path = doc.reference.path # this is a string
print(path)

Manipulating Google Cloud Firestore data in python

I'm trying to read a specific data field in Google Cloud Firestore using python.
I have a collection called Products in my Firestore DB, and have manually added several documents with various fields.
So far I am able to pull a document using:
docs = db.collection(u'Products').where(u'checked', u'==', False).stream()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
This works, and I receive the following output:
Test2 => {'link': 'https://stackoverflow.com', 'price': 14, 'checked': False}
However, I am unable to pull out the individual 'link' string from this dict. I have tried:
print(doc.to_dict('link'))
and several iterations of this, and get the following output:
to_dict() takes 1 positional argument but 2 were given
I have been following the firebase documentation here, but have found no examples of printing fields specifically.
Any advice on how to print the 'link' string from the query I have used?
I'm running Python 3.7.
Thanks in advance for your help.
to_dict returns a dict, so your code should probably look like:
print(doc.to_dict()['link'])
instead of passing the parameter directly.
Alternatively, since you only need the one field you can try:
print(doc.get('link'))
As it avoids creating a copy of the entire snapshot.

Pymongo.find() only return answer

I am working on a code which will fetch data from the database using pymongo. After that I'll show it in a GUI using Tkinter.
I am using
.find()
to find specific documents. However I don't want anything else then 'name' to show up. So I used {"name":1}, now it returns:
{u'name':u'**returned_name**'}
How do I remove the u'name': so it will only return returned_name?
Thanks in advance,
Max
P.s. I have searched a lot around the web but couldn't find anything which would give me some argument to help me.
What you see returned by find() call is a cursor. Just iterate over the cursor and get the value by the name key for every document found:
result = db.col.find({"some": "condition"}, {"name": 1})
print([document["name"] for document in result])
As a result, you'll get a list of names.
Or, if you want and expect a single document to be matched, use find_one():
document = db.col.find_one({"some": "condition"}, {"name": 1})
print(document["name"])
Mongo will return the data with keys, though you can as workaround use something like this
var result = []
db.Resellers_accounts.find({"name":1, "_id":0}).forEach(function(u) { result.push(u.name) })
This example is for NodeJS driver, similar can be done for Python
Edit (Python Code) -
res = db.Resellers_accounts.find({},{"name":1, "_id":0})
result = []
for each in res:
result.append(res['name'])
Edit 2 -
No pymongo doesn't support returning only values, everything is key-value paired in MongoDB.

TypeError: documents must be a non-empty list

I'm doing a program using Twitter API and MongoDB in 2.7 Python language.
I get a timeline and put it in a dictionary, which I want to store in a MongoDB database. To do this I have next code:
def saveOnBD(self, dic):
client = MongoClient("xxxx", "port")
db = client.DB_Tweets_User_Date
collection = db.tweets
collection.insert_many(dic)
I'm debbuging and dic it's not empty but I get next error:
TypeError: documents must be a non-empty list
How can I fix it?
I trying many options, but i solved that question changing the post method.
Instead of:
collection.insert_many(dic)
I used this:
collection.insert_one(dic)
I supose that, as I try to post only a variable(dic) and "insert_many()" is for many variables that retun me the error. That change solved me the question
you can either put in an entry before running the bulk entry function or use insert()
A list of documents must be passed to insert_many method
E.g.:
collection.insert_many([dic])

Categories

Resources