6

हम आप देख सकते हैं, क्वेरी नहीं डाली पिछले 20 रिकॉर्ड का एक संग्रह है हमारे Node.jsMongoDB में संग्रह का सहारा कैसे लें?

mongo.connect('mongodb://XXX:[email protected]:54289/XXXdb', function (err, db) { 
    var collection = db.collection('chatmessages') 
    var stream = collection.find().sort({ _id: -1 }).limit(20).stream(); 
    stream.on('data', function (chat) { 
     socket.emit('user message', chat.content, chat.dateCreated); 
    }); 
}); 

में यह निम्न क्वेरी था। लेकिन फिर इस परिणाम से हम _id में फिर से 1 तक रिसॉर्ट करना चाहते हैं, इसलिए सूची में हमारे पास आईडी (55) के लिए आईडी 55 - 75 होगा। तो आखिरी बार हमेशा नीचे।

हम इसे फिर से कैसे प्राप्त कर सकते हैं?

+0

आपके संग्रह में _id फ़ील्ड ObjectId प्रकार या संख्यात्मक है? –

+0

_id फ़ील्ड guid – dcpartners

+0

सरल समाधान है कि उन्हें पुनर्प्राप्त करने के बाद दस्तावेज़ों के क्रम को उलटना है। नीचे मेरा जवाब देखें। –

उत्तर

5

आपको एकत्रीकरण फ्रेमवर्क का उपयोग करने की आवश्यकता है।

mongo.connect('mongodb://XXX:[email protected]:54289/XXXdb', function (err, db) { 
    var collection = db.collection('chatmessages') 
    var stream = collection.aggregate([ 
     { "$sort": { "_id": -1}}, 
     { "$limit": 20 }, 
     { "$sort": { "_id": 1 }} 
    ]); 
    stream.on('data', function (chat) { 
     socket.emit('user message', chat.content, chat.dateCreated); 
    }); 
}); 
+0

इस बात का एहसास नहीं था कि इसके लिए एजगेट विधि है। धन्यवाद – dcpartners

2

करने के लिए सबसे आसान काम क्वेरी द्वारा लौटाए गए रिकॉर्ड के क्रम को उलट करना होगा। तो, स्ट्रीम प्राप्त करने के बजाय, सॉकेट के माध्यम से भेजने से पहले, इसमें रिकॉर्ड्स के क्रम को उलट करने के लिए, सरणी में प्रतिक्रिया को परिवर्तित करें और reverse() फ़ंक्शन का उपयोग करें!

mongo.connect('mongodb://XXX:[email protected]:54289/XXXdb', function (err, db) { 

    var collection = db.collection('chatmessages') 

    collection.find().sort({ _id: _1 }).limit(20).toArray(function(err, docs) { 

     if (err) { 
      // handle error 
     } 

     docs.reverse(); // <-- This will reverse the order of records returned! 


     // Send the the array of records through socket. 
     socket.emit('user message', docs) 

    }) 
}); 
संबंधित मुद्दे