如何在 MongoDB 中查詢前 N 行?


要在 MongoDB 中查詢前 N 行,可以使用聚合框架。我們用文件建立一個集合

> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca26eee6304881c5ce84b91")
}
> db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca26ef66304881c5ce84b92")
}
> db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca26efe6304881c5ce84b93")
}
> db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca26f066304881c5ce84b94")
}
> db.topNRowsDemo.insertOne({"StudentName":"John","Score":86});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca26f0f6304881c5ce84b95")
}

下面是使用 find() 方法顯示集合中所有文件的查詢

> db.topNRowsDemo.find().pretty();

這將產生以下輸出

{
   "_id" : ObjectId("5ca26eee6304881c5ce84b91"),
   "StudentName" : "Larry",
   "Score" : 78
}
{
   "_id" : ObjectId("5ca26ef66304881c5ce84b92"),
   "StudentName" : "Chris",
   "Score" : 45
}
{
   "_id" : ObjectId("5ca26efe6304881c5ce84b93"),
   "StudentName" : "Mike",
   "Score" : 65
}
{
   "_id" : ObjectId("5ca26f066304881c5ce84b94"),
   "StudentName" : "Adam",
   "Score" : 55
}
{
   "_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
   "StudentName" : "John",
   "Score" : 86
}

以下是在 MongoDB 中查詢前 N 行的方法

> db.topNRowsDemo.aggregate([
...    {$sort: {StudentName: 1}},
...    {$limit: 5},
...    {$match: {Score: {$gt: 65}}}
... ]).pretty();

這將產生以下輸出

{
   "_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
   "StudentName" : "John",
   "Score" : 86
}
{
   "_id" : ObjectId("5ca26eee6304881c5ce84b91"),
   "StudentName" : "Larry",
   "Score" : 78
}

更新於: 30-Jul-2019

3K+ 瀏覽

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.