I'm trying to pick out unique elements from a collection of objects and then save them to a sub collection.
The code I have is:
for item in db.col1.find({'Summary': {'$ne':{}}}):
current_specs = item['Summary']['Specs']
if not db.col1.specs.find({'Specs':current_specs}).count():
db.col1.specs.save({'Specs':current_specs, 'Updated': datetime.datetime.now()},safe=True)
This produces duplicate entries within db.col1.specs. I thought by using safe=True, it would make sure the write was completed and hence duplicates would not be added but this does not seem to be the case.
Can anyone explain why this is failing and the correct way of doing it?
Cheers
Figured it out:
the item['Summary']['Specs'] entry is itself a dictionary and to search for dictionaries you have to search for each individual dictionary entry
e.g. if the object looks like:
current_specs = {'field1': something, 'field2': something_else}
then we can find it via:
find({'Specs.field1':current_specs[field1], 'Specs.field2': current_specs[field2]})
you can't just use:
find({'Specs':current_specs})
Related
I'm making a scheduling app, and storing all the scheduled things in firebase with arrays. When I try to schedule something with the same string value, it fails and doesn't add it to the array. I don't know if this is something in swift I can edit, or if it's a firebase setting.
If it's something in swift, here's the code updating the array:
doc.updateData([
"Instructor": FieldValue.arrayUnion(["\(scheduleinstructor)"])
])
If it's something in firebase, could someone please explain a way around this or a simple fix I overlooked?
According to the documentation on adding items to an array:
arrayUnion() adds elements to an array but only elements not already present
So the fact that the duplicate entry is not added is by design. If you want to allow that, you'll have to:
Read the document with the array from the databae.
Extract the array from the document into your application code.
Add the item to the array.
Write the entire modified array back to the database.
I've finally started to understand a lot of info regarding FireStore, but I'm wondering if I can get some assistance.
If I had a setup similar to or like this:
races
Android
name: Android
size: medium
stats <---- this is the map
str: 10
sex: 12.... (more values)
How would I parse this? I am looking to make specific TextViews apply values found in the database so that I can simply update the database and my app will populate those values so that hard coding and code updating won't be nearly as troublesome in the future.
I currently use something like this:
val androidRef = db.collection("races").document("Android")
androidRef.get().addOnSuccessListener { document ->
if (document != null) {
oneOfTheTextViews.text = document.getString("str")
} else {
}
The issue is currently I can only seem to access from collection (races) / document (android) / then a single field (I have "str" set as a single field, not part of a map or array)
What would the best practice be to do this? Should I not nest them at all? And if I can reference said nesting/mapping/array, what functions need to be called? (To be clear, I am not asking only whether or not it is possible - the reference guides and documents allude to such - but what property/class/method/etc needs to be called in order to access only one of those values or point to one of those values?).
Second question: Is there a way to get a list of document names? If I have several races, and simply want to make a spinner or recycler view based on document names as part of a collection, can I read that to the app?
What would the best practice be to do this?
If you want to get the value of your str property which is nested within your stats map, please change the following line of code:
oneOfTheTextViews.text = document.getString("str")
to
oneOfTheTextViews.text = document.getString("stats.str")
If your str property is a number and not a String, then instead of the above line of code please use this one:
oneOfTheTextViews.text = document.getLong("stats.str")
Should I not nest them at all?
No, you can nest as many properties as you want within a Map.
Is there a way to get a list of document names?
Yes, simply iterate the collection and get the document ids using getId() function.
I am trying to access and cache (set) the value element in a paginated dictionary. I want each new paginated dictionary to do this. There is a way to go through the dictionaries with "before" and "after" parameters, but I think that might be an unnecessary tidbit.
When I do this:
[{x:1,y:2}]
pag_dict = foo.get_dict()
xvalue = bar.set(pag_dict["x"])
print(xvalue)
I get "TypeError: list indices must be integers or slices, not str" for the line with xvalue = bar.set(pag_dict["x"]). I just need it to print out 1 by accessing x.
I keep running into problems every way I try to fix this. Help would be extremely appreciated.
Thank you!
Based on discussion in comment:
pag_dict = [[{'x': 1, 'y': 2}]]
The above shows pag_dict is a list of list with 1 element. The element is of type Python's dict, which is a key-value pairs.
To get value of key x, try this:
# this gives "1"
pag_dict[0][0]['x']
I'm new to Firebase and have a function that writes all of my event ID's to an array. I want to use the last value in that array (the last event ID) to lookup the children of that specific eventID.
I know how to get the last item in the array but how do I put that into my .child() path?
I tried the code below, but it doesn't seem to work. I'm guessing that because .child("(lastEvent)") isn't a valid path.
let lastEvent = eventIDArray.last
refHandle = ref.child("Bouts").child("\(lastEvent)")
How do I plug the lastEvent value in as my path? Or is that even possible? Again, total newbie- alternatives welcome.
Sorting and filtering data
you can use sorting and filtering function to get the item.
To get the last item you can write the query like this.**
let recentBoutsQuery = (ref?.child("Bouts").queryLimited(toLast: 1))!
This will return 1 entry from last of your database which the last entry.
You can learn more from the firebase documentation. Work with Lists of Data
I basically want to write logic such that if certain element is already present in array i dont want to again put it into it. My array is one dimensional. I am not able to understand how filter function works. Please help. Thanks.
I'm not sure I exactly get what you are trying to do.
But what I understand makes me recommend you to use Dictionary (it is basically a Hashmap)
It works with keys and values.
Each element of this Dictionary contains a unique key (a String that is used to access specifically the data you want) and a value attached to it (can be a String, a Number...)
Here is how to use it :
in your VBA page, go to Tools -> References -> add "Microsoft Scripting Runtime" from the list of available references.
Then in your code :
Dim myDico as Dictionary
set myDico = new Dictionary
myDico.add "myKey", 5
msgbox myDico.Item("myKey") '5