使用嵌套结果

时间:2018-06-14 06:43:50

标签: python mongodb aggregation-framework

我有这个mongo查询:

def datetime_1(x):
return np.array(x, dtype='datetime64')

p1 = figure(x_axis_type="datetime", title="Stock Closing Prices")
p1.grid.grid_line_alpha=0.7 #spessore griglia
p1.xaxis.axis_label = 'Datetime'
p1.yaxis.axis_label = 'Value'

timestamp_var1 = []
timestamp_var2 = []
timestamp_var3 = []
values_var1 = []
values_var2 = []
values_var3 = []
ms = 0
i = 0

t1 = datetime.datetime(2018,1,1,15,30,0,0)
t2 = datetime.datetime(2018,1,1,15,31,0,0)

#results = collection.find( { "timestamp": { "$gte": t1, "$lt": t2 } } )
results = collection.aggregate([{ '$lookup': {'from':"zlib_var2", 'localField': "timestamp", 'foreignField': "timestamp", 'as':"results"}}, { '$unwind': { 'path': "$results", 'preserveNullAndEmptyArrays': False }},{ '$unwind': { 'path': "$results", 'preserveNullAndEmptyArrays': False }},  {'$match':{"timestamp": { "$gte": t1, "$lt": t2 }}}])
t = t1
with open('result.json','a') as file:
    for item in results:
        file.write(str(item))

例如,如果我得到两个文档,则第二个嵌套在“结果”字段下的第一个文档中。相反,我想要一份简单的文件清单。 查询的一个示例是:

{
    '_id': ObjectId('5b1fcc8480487e2aa8aa1ade'), 
    'area_id': 'a long area id goes here', 
    'plant_id': 'a long plant id goes here', 
    'heatid': 2221, 
    'product_id': 1112, 
    'variables': 'var2', 
    'timestamp': datetime.datetime(2018, 1, 1, 15, 30), 
    'data': {
        '0': 8.040029047075672, 
        '50': 82.68379959402783, 
        ....}, 
        'results': {
            '_id': ObjectId('5b1fc38a732d8921d4dbf671'), 
            'area_id': 'a long area id goes here', 
            'plant_id': 'a long plant id goes here',
             'heatid': 1122, 'product_id': 2211, 
             'variables': 'var2', 
             'timestamp': datetime.datetime(2018, 1, 1, 15, 30), 
             'data': {....}
        }
    }
}

我哪里错了?

谢谢:)

编辑: 对不完整的问题感到抱歉,我想要的结果是:

{
    '_id': ObjectId('5b1fcc8480487e2aa8aa1ade'), 
    'area_id': 'a long area id goes here', 
    'plant_id': 'a long plant id goes here', 
    'heatid': 2221, 
    'product_id': 1112, 
    'variables': 'var2', 
    'timestamp': datetime.datetime(2018, 1, 1, 15, 30), 
    'data': {
        '0': 8.040029047075672, 
        '50': 82.68379959402783, 
        ....}
},
{ 
    '_id': ObjectId('5b1fc38a732d8921d4dbf671'), 
    'area_id': 'a long area id goes here', 
    'plant_id': 'a long plant id goes here',
    'heatid': 1122, 
    'product_id': 2211, 
    'variables': 'var2', 
    'timestamp': datetime.datetime(2018, 1, 1, 15, 30), 
    'data': {....}
}

0 个答案:

没有答案