如何使用位置插入MongoDB集合 [英] How to insert to a MongoDB collection with a position

查看:53
本文介绍了如何使用位置插入MongoDB集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向MongoDB集合中插入不同的项目,但我希望将项目插入到数组的顶部,这样在检索集合项目时我可以对它们进行排序。

I'm trying to insert different items to a MongoDB collection, but I want to the item to be inserted at the top of the array so when retrieving the collection items I can get them sorted.

我正在使用此代码:

 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);
  }


});

此代码用于检索收藏品:

And this code to retrieve collection items :

 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

I insert new items each 10 minutes, and when I retrieve items I want the last item inserted to be at the position 0

推荐答案

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

You should just write a query for the data that you want. The $orderby operator will sort the data any way you like.

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

如果你真的需要最后一项,你可以限制查询到一个结果。请注意,此版本也使用排序功能

If you really just need the last item, you could limit the query to one result as well. Note that this version uses the sort function as well.

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

这篇关于如何使用位置插入MongoDB集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆