MongoDB相当于这个SQL查询

时间:2018-03-26 14:34:41

标签: mongodb

我想知道如何在MongoDB中运行等效的以下SQL查询。

// 1 = current user ID

SELECT p.id, p.firstName, p.lastName from friendships f
JOIN person p ON p.id = f.requester
WHERE f.requestee = 1
UNION
SELECT p.id, p.firstName, p.lastName
from friendships f
JOIN person p ON p.id = f.requestee
WHERE f.requester = 1

友谊表

╔══════════════════════════════════════╗
║ requester       requestee       type ║
╠══════════════════════════════════════╣
║ userA           userC            1   ║
║ userB           userA            1   ║
║ userC           userD            1   ║
╚══════════════════════════════════════╝

假设我userA我的朋友是根据上表userBuserC,我需要返回这两个用户。

MongoDB友情文件(收集友谊)

{
    requester: userID
    requestee: otherUserID
    type: // type of relationship (accepted, declined, blocked, etc.)
    time: // timestamp
}

MongoDB用户文档(集合用户)

{
    _id: ObjectId('random')
    firstName: 'Someone',
    lastName: 'Random'
}

期望的结果:当前用户的所有朋友及其用户详细信息。

[
    {
        firstName: 'John'
        lastName: 'Doe'
        time: // timestamp from friendship document
    },
    {
        firstName: 'Jane'
        lastName: 'Doe'
        time: // timestamp from friendship document
    },
    {
        firstName: 'James'
        lastName: 'Doe'
        time: // timestamp from friendship document
    }
]

非常感谢您提前寻求帮助。

1 个答案:

答案 0 :(得分:1)

这是基于问题中可用信息的部分答案。您可能需要根据需要进行更改。任何改进都表示赞赏。

db.friendship.aggregate([
{ 
      $lookup:{  
         from:"person",
         as: "p1",
         localField: "personid1",
         foreignField: "personid",
      }
    },
    { 
      $lookup:{  
         from:"person",
         as: "p2",
         localField: "personid2",
         foreignField: "personid",
      }
    },
    {
        $match:{ $or: [{personid1:"1"},{personid2:"1"}]}
    },
    {
        $replaceRoot:{ newRoot: {
            "persons" : { $setUnion : [ "$p1" , "$p2" ]}
        }
        }
    },{
        $unwind:{  path: "$persons"}
    },
    {
        $group:{ _id: {personid:"$persons.personid", firstname:"$persons.firstname", lastname:"$persons.lastname"} }
    },
    {
        $replaceRoot:{ newRoot: {
            "personid" : "$_id.personid",
            "firstname" : "$_id.firstname",
            "lastname" : "$_id.lastname"
        }
        }
    }
]).pretty()