Node 和 MongoDB——對記錄進行排序



要對集合的選定文件進行排序,可以使用 collection.find().sort() 方法對文件進行排序。

database.collection("sampleCollection").find({}).sort({First_Name: -1}).toArray(function(error, result) {
   if (error) throw error;
   console.log(result);
});

示例

嘗試以下示例在一個 mongodb 集合中選擇有限的文件:

將以下示例複製並貼上作為 mongodb_example.js:

const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Connect to the database
   const database = client.db('myDb');   
   database.collection("sampleCollection").find({}).sort({First_Name: -1}).toArray(function(error, result) {
      if (error) throw error;
      console.log(result);
   });  
   // close the connection
   client.close();
});

輸出

使用 node 執行 mysql_example.js 指令碼,並驗證輸出。

node mongodb_example.js
Connected!
[
  {
    _id: 60c4bbb40f8c3920a0e30fdd,
    First_Name: 'Radhika',
    Last_Name: 'Sharma',
    Date_Of_Birth: '1995-09-26',
    e_mail: 'radhika_sharma.123@gmail.com',
    phone: '9000012345'
  },
  {
    _id: 60c4bbb40f8c3920a0e30fde,
    First_Name: 'Rachel',
    Last_Name: 'Christopher',
    Date_Of_Birth: '1990-02-16',
    e_mail: 'rachel_christopher.123@gmail.com',
    phone: '9000054321'
  },
  {
    _id: 60c4bbb40f8c3920a0e30fdf,
    First_Name: 'Fathima',
    Last_Name: 'Sheik',
    Date_Of_Birth: '1990-02-16',
    e_mail: 'fathima_sheik.123@gmail.com',
    phone: '9000012345'
  }
]
廣告