2014-11-04 5 views
5

Diciamo che ho un database Mongo di messaggi che assomiglia a questo:Listing l'ultimo messaggio di ogni conversazione, che coinvolge un utente, in MongoDB

{ 
    "_id": ObjectId("5458009c1ab2354c029d7178"), 
    "to": "dan", 
    "from": "wood", 
    "message": "hi dan how are you?", 
    "time": new Date(1415053468590), 
    "__v": 0 
} 
{ 
    "_id": ObjectId("545800b45eaf364d026c1cba"), 
    "to": "wood", 
    "from": "dan", 
    "message": "hi wood how are you?", 
    "time": new Date(1415053492125), 
    "__v": 0 
} 
{ 
    "_id": ObjectId("5458009c1ab2354c029d7178"), 
    "to": "billy", 
    "from": "wood", 
    "message": "hi billy how are you?", 
    "time": new Date(1415053468590), 
    "__v": 0 
} 
{ 
    "_id": ObjectId("545800b45eaf364d026c1cba"), 
    "to": "wood", 
    "from": "billy", 
    "message": "hi wood how are you?", 
    "time": new Date(1415053492125), 
    "__v": 0 
} 

Così come posso recuperare l'ultimo messaggio da ogni conversazione che l'utente "legno" può avere?

Qualcun altro ha già postato una domanda simile su come farlo in mysql. Sto chiedendo come farlo in mangusta.

Io posto che per riferimento in caso aiuta: Private messaging system. Listing last message of each conversation

sarebbe bello se potesse dare una mano. Grazie per l'aiuto. Lo apprezzo molto. Sono nuovo di mangusta, mongodb e node.js. Vengo da uno sfondo php mysql.

Sarebbe bello se potessi pubblicare il codice effettivo su come farlo in modo che io possa provarlo e fornire un feedback. Grazie.

mio schema di database si presenta così:

var messageSchema = new Schema({ 
to: { type: String, required: true}, 
from: { type: String, required: true}, 
message: { type: String, required: true}, 
time : { type : Date, default: Date.now } 
}); 

prova di che tipo di persone eseguire questo sito: http://i62.tinypic.com/bbntx.jpg

Lasciando questo sito web come si può dire che tipo di persone ostili sono funzionamento di questo sito . Probabilmente mi chiederò da qualche altra parte. A loro non importa davvero di aiutarti. Si preoccupano delle loro regole. Sei una persona nuova che non ti danno il benvenuto. Mi piacerebbe essere accolto da nessun'altra parte, non trattato come la sporcizia come fanno le persone qui.

risposta

6

Benvenuti in overflow dello stack. È una domanda decente, hai postato. Per favore lasciami prendere il privilegio di aiutarti nel modo in cui posso.

Questo è un comando di aggregazione che può essere eseguito nella shell mongo. Si prega di trovare la spiegazione in linea.

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"} 
    } 
} 
]) 

È possibile eseguire il seguente su mangusta.

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); 
} 
) 
+0

sei un viaggiatore del tempo? –

+0

@ T.Rex - :) perché me lo chiedi? – BatScream

+0

Mi dispiace per quello :) Proprio come avevi iniziato, come un gentiluomo inglese molto educato da prima che il decoro diventasse fuori moda. –

Problemi correlati