MongoDB
 sql >> डेटाबेस >  >> NoSQL >> MongoDB

MongoDB में प्रत्येक वार्तालाप के अंतिम संदेश को सूचीबद्ध करना, जिसमें एक उपयोगकर्ता शामिल है

स्टैक ओवरफ्लो में आपका स्वागत है। यह एक अच्छा सवाल है, आपने पोस्ट किया। कृपया मुझे आपकी हर संभव मदद करने का विशेषाधिकार दें।

यह एक एग्रीगेशन कमांड है जिसे मोंगो शेल में चलाया जा सकता है। कृपया स्पष्टीकरण इनलाइन देखें।

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. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. MongoDB डालने के प्रदर्शन में सुधार कैसे करें

  2. एक बड़ी जोंस फ़ाइल के माध्यम से ठीक से पुनरावृति कैसे करें

  3. MongoDB को DynamoDB में माइग्रेट करना, भाग 1

  4. mongodb में $match _id . में एग्रीगेट का उपयोग कैसे करें

  5. नेवला में __v फ़ील्ड क्या है