鍍金池/ 問答/Python  數(shù)據(jù)庫(kù)/ 通過Pymongo如何多表關(guān)聯(lián)查詢數(shù)據(jù)?

通過Pymongo如何多表關(guān)聯(lián)查詢數(shù)據(jù)?

MongoDB數(shù)據(jù)庫(kù)多表查詢數(shù)據(jù)

之前在Robo 3T里通過 $lookup可以把2個(gè)表關(guān)聯(lián)

相關(guān)代碼

db.users.aggregate([
{    $match : 
    { regDate : { "$gte" : ISODate("2018-05-01T00:00:00Z"), "$lt" : ISODate("2018-05-31T00:00:00Z") } }
},
{
    $project :
    {    
        '_id':1,
        'regDate':1,
        'totalRecharge':1,
        'jcode':1
    }
},
{
$lookup:
    {
        "from":"recharge",
        "localField":"_id",
        "foreignField":"uid",
        "as":"recharge"
    }
},
{ $match : {"recharge.from" : "weixin"}},
{ $match : {"recharge.from" : "alipay"}},
{ $match : {"recharge.rechargeDate" : {"$gte" : ISODate("2018-05-01T00:00:00Z"), "$lt":ISODate("2018-05-31T00:00:00Z")}}},

])

users是用戶表,recharge是充值表,用戶表里沒有充值金額(real)以及充值日期(rechargeDate),充值表里沒有用戶注冊(cè)時(shí)間。

想查詢哪些是充值用戶和在時(shí)間范圍內(nèi)(注冊(cè)1周、3周等)之內(nèi)哪些充值過。

回答
編輯回答
醉淸風(fēng)

最簡(jiǎn)單的辦法是把用戶注冊(cè)信息冗余到充值記錄里面,根本就不用$lookup了,性能可以提高很多。畢竟注冊(cè)時(shí)間又不會(huì)變。

2018年4月24日 13:21
編輯回答
任她鬧

這個(gè)要求本身就有些強(qiáng)人所難,非關(guān)系型數(shù)據(jù)庫(kù)對(duì)多表查詢這種復(fù)雜的查詢方式都是乏善可陳的,也要盡量避免這種查詢方式,建議與 ES 配合使用,或者將查詢結(jié)果緩存。

2017年8月18日 06:25