【问题标题】:How to insert to a MongoDB collection with a position如何插入具有位置的 MongoDB 集合
【发布时间】:2015-10-15 06:55:50
【问题描述】:

我正在尝试将不同的项目插入到 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

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

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

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

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

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

    【讨论】:

    • @YasserB。很高兴我能帮上忙。如果对您有帮助,请不要忘记接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2017-08-08
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多