MongoDB - 获取消息线程

时间:2015-10-14 18:13:25

标签: php mongodb aggregation-framework

邮件集合:

{ "members": ["userA", "userB"], "content": "Some message" },
{ "members": ["userA", "userC"], "content": "Some message" },
{ "members": ["userA", "userB"], "content": "Some message 2" }

如果我想通过userA查找邮件主题,我希望得到以下结果:["UserB", "UserC"]

public function findUserThreads($user)
    {
        $data = $this->getCollection()->find(['members' => $user]);
        $threads = [];
        while($data->hasNext()){
            $msg = $data->getNext();
            if($msg['members'][0] != $user) {
                $threads[] = $msg['members'][0];
            }
            if($msg['members'][1] != $user) {
                $threads[] = $msg['members'][1];
            }
        }

        return array_values(array_unique($threads));
    }

我想在mongodb中这样做,而不是在php中。

1 个答案:

答案 0 :(得分:1)

那么你需要使用.aggregate()方法。

db.users.aggregate([
    { "$match": { "members": "userA" }},
    { "$project": { 
        "users": { "$setDifference": [
            { "$map": { 
                "input": "$members", 
                "as": "m", 
                "in": { "$cond": [ 
                    { "$ne": [ "$$m", "userA" ] },
                    "$$m", 
                    false ]
                }
            }}, 
            [false]
        ]}
    }}, 
    { "$unwind": "$users" }, 
    { "$group": { 
        "_id": null, 
        "users": { "$addToSet": "$users"}
    }}
])

返回:

{ "_id" : null, "users" : [ "userC", "userB" ] }