如何插入一个位置的MongoDB集合

我试图插入不同的项目到MongoDB集合,但我想要项目被插入在数组的顶部,所以当检索收集项目,我可以让他们sorting。

我正在使用这个代码:

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

你应该只是写一个你想要的数据的查询。 $orderby操作符将按照您喜欢的方式对数据进行sorting。

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

如果你真的只需要最后一项,你可以限制查询结果。 请注意,该版本也使用sortingfunction 。

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