-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathhelpers.py
68 lines (53 loc) · 1.84 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import bson, struct
import itertools
from bson.errors import InvalidBSON
# Helper functions work working with bson files created using mongodump
def bson_iter(bson_file):
"""
Takes a file handle to a .bson file and returns an iterator for each
doc in the file. This will not load all docs into memory.
with open('User.bson', 'rb') as bs:
active_users = filter(bson_iter(bs), "type", "active")
"""
while True:
size_str = bson_file.read(4)
if not len(size_str):
break
obj_size = struct.unpack("<i", size_str)[0]
obj = bson_file.read(obj_size - 4)
if obj[-1] != "\x00":
raise InvalidBSON("bad eoo")
yield bson._bson_to_dict(size_str + obj, dict, True)[0]
def _deep_get(obj, field):
parts = field.split(".")
if len(parts) == 1:
return obj.get(field)
last_value = {}
for part in parts[0:-1]:
last_value = obj.get(part)
if not last_value:
return False
if isinstance(last_value, dict):
return last_value.get(parts[-1])
else:
return getattr(last_value, parts[-1])
def groupby(iterator, field):
"""
Returns dictionary with the keys beign the field to group by
and the values a list of the group docs.
This is useful for converting a list of docs into dict by _id
for example.
"""
groups = {}
for k, g in itertools.groupby(iterator, lambda x: _deep_get(x, field)):
items = groups.setdefault(k, [])
for item in g:
items.append(item)
return groups
def filter(iterator, field, value):
"""
Takes an iterator and returns only the docs that have a field == value.
The field can be a nested field like a.b.c and it will descend into the
embedded documents.
"""
return filter(lambda x: _deep_get(x, field) == value, iterator)