sql >> データベース >  >> NoSQL >> MongoDB

MongoDBで、ユーザーが関与する各会話の最後のメッセージを一覧表示する

    Stackoverflowへようこそ。それはまともな質問です、あなたは投稿しました。できる限りのお手伝いをさせていただきます。

    これは、mongoシェルで実行できる集約コマンドです。説明をインラインで見つけてください。

    db.collection.aggregate([
    //match all those records which involve Wood.
    {$match:{$or:[{"to":"wood"},{"from":"wood"}]}},
    // sort all the messages by descending order
    {$sort:{time:-1}},
    {
        // Now we need to group messages together, based on the to and from field.
        // We generate a key - "last_message_between", with the value being a concatenation
        // result of the values in to and from field.
        // Now, Messages from Wood to billy and Billy to wood should be treated under a single group right.
        // To achieve that, we do a small trick to make the result contain the name coming last
        // alphabetically, first. So our key for all the Messages from Wood to Billy and Billy to Wood would be 
        // "Wood and Billy".
        // And then we just display the first document that appears in the group, that would be the 
        // latest Message.
        $group:{"_id":{
        "last_message_between":{
            $cond:[
                {
                    $gt:[
                    {$substr:["$to",0,1]},
                    {$substr:["$from",0,1]}]
                },
                {$concat:["$to"," and ","$from"]},
                {$concat:["$from"," and ","$to"]}
            ]
        }
        },"message":{$first:"$$ROOT"}
        }
    }
    ])
    

    マングースで以下を実行できます。

    Collection.aggregate(
    {$match:{$or:[{"to":"wood"},{"from":"wood"}]}},
    {$sort:{time:-1}},
    {
        $group:{"_id":{
        "last_message_between":{
            $cond:[
                {
                    $gt:[
                    {$substr:["$to",0,1]},
                    {$substr:["$from",0,1]}]
                },
                {$concat:["$to"," and ","$from"]},
                {$concat:["$from"," and ","$to"]}
            ]
        }
        },"message":{$first:"$$ROOT"}
        }
    },
    function(err, res)
    {
        if (err) return handleError(err);
        console.log(res);
    }
    )
    



    1. ServiceStack:サービスを手動で呼び出すときにパイプラインを復元しますか?

    2. MongoDBサーバーには、資格情報がなくてもアクセスできます

    3. Laravel 4:未定義のメソッドRedis ::connection()の呼び出し

    4. MongoDBとCodeIgniter