我已经使用聚合在 mongodb 中编写了一个查询,该查询工作正常,但不知怎的,它在我的 python 代码中使用 pymongo 时无法正常工作。请指教如何纠正。
蒙戈查询:
db.flights.aggregate([
{ $match: { origin:"ATL", dest:"BOS",dayofweek: 3} },
{ $group: {
_id: {
origin:"$origin",
destination: "$dest"
},
Failure: { $sum: { $cond : [{ $eq : ["$cancelled", 1]}, 1, 0]} },
Success: { $sum: { $cond : [{ $eq : ["$cancelled", 0]}, 1, 0]} },
Total: { $sum: 1 }
} },
{$project:{Failure:1,Success:1, Total:1, FailPercent: { $divide: [ "$Failure", "$Total" ]}}},
{ $sort: { "_id.origin": 1, "_id.destination": 1 } }
])
在Python代码中:
client = MongoClient("localhost", 27017)
connect = client["database"]["collection"]
pipe2 = [ { '$match': { 'origin':"ATL", 'dest':"BOS",'dayofweek': 3} },
{ '$group': {
'_id': {
'origin':"$origin",
'destination': "$dest"
},
'Failure': { '$sum': { '$cond' : [{ '$eq' : ["$cancelled", 1]}, 1, 0]} },
'Success': { '$sum': { '$cond' : [{ '$eq' : ["$cancelled", 0]}, 1, 0]} },
'Total': { '$sum': 1 }
} },{'$project':{'Failure':1,'Success':1, 'Total':1, 'FailPercent': { '$divide': [ "$Failure", "$Total" ]}}},
{ '$sort': SON([("_id.origin", 1), ("_id.destination", 1 )]) }
]
result = connect.aggregate(pipeline=pipe2)
pymongo 的查询结果不正确,但在 mongoDB 中是正确的
最佳答案
“管道”变量似乎没有必要。没有看到您的错误,并假设您与数据库的连接正常
这一行:
result = connect.aggregate(pipeline=pipe2)
应该是:
result = connect.aggregate(pipe2)
根据所提供的信息复制您的收藏后,这对我有用。这是完整的代码(我的连接看起来也与你的有点不同)
集合:
{ '_id' : 1, 'origin' : 'ATL', 'dest' : 'BOS', 'dayofweek' : 3, 'cancelled' : 0 }
{ '_id' : 2, 'origin' : 'ATL', 'dest' : 'BOS', 'dayofweek' : 3, 'cancelled' : 0 }
{ '_id' : 3, 'origin' : 'ATL', 'dest' : 'BOS', 'dayofweek' : 3, 'cancelled' : 1 }
代码:
import pymongo
from bson.son import SON
connection_string = 'mongodb://localhost'
connection = pymongo.MongoClient(connection_string)
database = connection.myDatabase
pipe2 = [ { '$match' : { 'origin' : 'ATL',
'dest' : 'BOS',
'dayofweek' : 3
}
},
{ '$group' : { '_id' : { 'origin' : '$origin',
'destination' : '$dest'
},
'Failure' : { '$sum' : { '$cond' : [{ '$eq' : ['$cancelled', 1]}, 1, 0 ]} },
'Success' : { '$sum' : { '$cond' : [{ '$eq' : ['$cancelled', 0]}, 1, 0 ]} },
'Total' : { '$sum' : 1 }
}
},
{ '$project' : { 'Failure' : 1,
'Success' : 1,
'Total' : 1,
'FailPercent' : { '$divide' : [ '$Failure', '$Total' ] }
}
},
{ '$sort' : SON([('_id.origin', 1), ('_id.destination', 1 )]) }
]
result = database.myCollection.aggregate(pipe2)
print(result)
输出:
{u'ok' : 1.0, u'result' : [{u'Failure': 1, u'_id': { u'origin': u'ATL', u'destination': u'BOS'}, u'FailPercent': 0.333333333333, u'Success': 2, u'Total': 3}]}
关于mongodb - PyMongo 聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075055/