Created
March 5, 2014 22:03
-
-
Save neuman/9377579 to your computer and use it in GitHub Desktop.
EmbeddedMixin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EmbeddedMixin(object): | |
def get_embedded(self, hierarchy, key, value, depth=0, indexes=False): | |
"""get a list containing the ordered indexes of embedded documents. | |
A recursive depth first search replacing the nested for loops normally required | |
to iterate through nested objects contained within lists to find a single object | |
that has a specific value for a specific key. | |
Keyword Arguments: | |
hierarchy -- a list of keys needed to access the list containingthe next level of objects to search | |
key -- the string name of the member to match value too | |
value -- the value that key is being matched too | |
indent -- used to make the print easy to read | |
indexes -- if True, return a list of indexes ordered the same as the hierarchy, | |
useful for targeting/updating embedded mongo documents | |
""" | |
index = 0 | |
domain = hierarchy.pop(0) | |
if len(hierarchy) == 0: | |
# if we're at the lowest level of the hierarchy, compare the key and value | |
for embedded in self[domain]: | |
if embedded[key] == value: | |
if indexes == True: | |
return [index] | |
else: | |
return embedded | |
index += 1 | |
else: | |
for embedded in self[domain]: | |
#if the key and value matched at a lower level, add this level's index to the address list | |
output = embedded.get_embedded(hierarchy, key, value, depth=depth + 1, indexes=indexes) | |
if output != None: | |
if indexes == True: | |
output.insert(0, index) | |
return output | |
else: | |
return output | |
index += 1 | |
hierarchy.insert(0, domain) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment