2015-10-14 104 views
1

我試圖插入不同的項目到一個MongoDB集合,但我想要在該數組的頂部插入項目,以便檢索收集項目,我可以得到他們排序。如何插入到一個位置的MongoDB集合

我使用這個代碼:

var json = { title : title, postid : postid, image : image, decription : description}; 

     collection.insert(json, function (err, result) { 
    if (err) { 
    console.log(err); 
    } else { 
    console.log('Here we go', result.length, result); 
    } 


}); 

而這個代碼來檢索收集物品:

collection.find().toArray(function (err, result) { 
     if (err) { 
     console.log(err); 
     } else if (result.length) { 
      first_item = result[0].postid; 
     console.log('Found:',first_item); 

     } else { 
     } 
    db.close(); 
    }); 
    } 
}); 

我插入新的項目,每次10分鐘,當我取回物品我想最後插入到位置0的項目

回答

1

您應該只爲所需的數據編寫查詢。 $orderby operator將按照您喜歡的方式對數據進行排序。

collection.find({ $query: {}, $orderby: { postid: -1 } }); 

如果你真的只需要在最後一個項目,你可以limit查詢到一個結果爲好。請注意,該版本也使用sort function

collection.find().sort({ postid: -1 }).limit(1); 
+0

謝謝!它完美的作品 –

+0

@YasserB。很高興我能幫上忙。如果有幫助,請不要忘記接受答案。 –

相關問題