首页 文章

如何使用位置插入MongoDB集合

提问于
浏览
1

我正在尝试向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 回答

  • 1

    您应该只为所需的数据编写查询 . $orderby operator将按您喜欢的方式对数据进行排序 .

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

    如果你真的只需要最后一项,你也可以limit查询一个结果 . 请注意,此版本也使用sort function .

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

相关问题