@@ -33,28 +33,25 @@ def create_key(timestamp, metadata):
33
33
collection = db [collection_name ]
34
34
for document in collection .find ({"timestamp" : {"$gte" : start_date , "$lt" : end_date }}):
35
35
unit = document ["metadata" ].get ("unit" )
36
- new_document = {
37
- "metadata" : {
38
- "device_id" : document ["metadata" ]["device_id" ],
39
- "name" : document ["metadata" ].get ("name" ),
40
- "user_id" : document ["metadata" ].get ("user_id" ),
41
- },
42
- new_collections [collection_name ]: document .get (old_collections [collection_name ]),
43
- "timestamp" : document ["timestamp" ],
44
- }
45
- if unit :
46
- new_document [f"{ new_collections [collection_name ]} _unit" ] = unit
47
-
48
36
key = create_key (document ["timestamp" ], document ["metadata" ])
49
37
50
- if key in buffer :
51
- buffer [key ][new_collections [collection_name ]] = document .get (
52
- old_collections [collection_name ]
53
- )
54
- if unit :
55
- buffer [key ][f"{ new_collections [collection_name ]} _unit" ] = unit
56
- else :
57
- buffer [key ] = new_document
38
+ # This will check if a buffer entry exists for the given timestamp and metadata
39
+ # If it doesn't exist, it initializes a new dictionary for it
40
+ if key not in buffer :
41
+ buffer [key ] = {
42
+ "metadata" : {
43
+ "device_id" : document ["metadata" ]["device_id" ],
44
+ "name" : document ["metadata" ].get ("name" ),
45
+ "user_id" : document ["metadata" ].get ("user_id" ),
46
+ },
47
+ "timestamp" : document ["timestamp" ],
48
+ }
49
+
50
+ buffer [key ][new_collections [collection_name ]] = document .get (
51
+ old_collections [collection_name ]
52
+ )
53
+ if unit :
54
+ buffer [key ][f"{ new_collections [collection_name ]} _unit" ] = unit
58
55
59
56
all_documents = sorted (buffer .values (), key = itemgetter ("timestamp" ))
60
57
0 commit comments