简体   繁体   中英

How to insert to a MongoDB collection with a position

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.

I'm using this code :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM