在 MongoDB 中獲取不同的記錄值?


您可以在 MongoDB 中使用 distinct() 方法來獲取不同的記錄值。語法如下 -

db.yourCollectionName.distinct(“yourFieldName”);

為了理解上述語法,讓我們建立一個帶有文件的集合。建立帶有文件的集合的查詢如下 -

> db.distinctRecordDemo.insertOne({"StudentId":1,"StudentName":"John","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a78299b97a65744c1b50")
}
> db.distinctRecordDemo.insertOne({"StudentId":2,"StudentName":"John","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a78b99b97a65744c1b51")
}
> db.distinctRecordDemo.insertOne({"StudentId":3,"StudentName":"Carol","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a79a99b97a65744c1b52")
}
> db.distinctRecordDemo.insertOne({"StudentId":4,"StudentName":"Carol","StudentAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7a499b97a65744c1b53")
}
> db.distinctRecordDemo.insertOne({"StudentId":5,"StudentName":"Sam","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7b499b97a65744c1b54")
}
> db.distinctRecordDemo.insertOne({"StudentId":6,"StudentName":"Mike","StudentAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7c799b97a65744c1b55")
}
> db.distinctRecordDemo.insertOne({"StudentId":7,"StudentName":"Sam","StudentAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77a7d399b97a65744c1b56")
}

在集合中顯示所有文件,藉助 find() 方法。查詢如下 -

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

以下為輸出

{
   "_id" : ObjectId("5c77a78299b97a65744c1b50"),
   "StudentId" : 1,
   "StudentName" : "John",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c77a78b99b97a65744c1b51"),
   "StudentId" : 2,
   "StudentName" : "John",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c77a79a99b97a65744c1b52"),
   "StudentId" : 3,
   "StudentName" : "Carol",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c77a7a499b97a65744c1b53"),
   "StudentId" : 4,
   "StudentName" : "Carol",
   "StudentAge" : 26
}
{
   "_id" : ObjectId("5c77a7b499b97a65744c1b54"),
   "StudentId" : 5,
   "StudentName" : "Sam",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c77a7c799b97a65744c1b55"),
   "StudentId" : 6,
   "StudentName" : "Mike",
   "StudentAge" : 27
}
{
   "_id" : ObjectId("5c77a7d399b97a65744c1b56"),
   "StudentId" : 7,
   "StudentName" : "Sam",
   "StudentAge" : 28
}

以下是獲取 MongoDB 中不同記錄值的方法。

案例 1 - 這裡的欄位是“StudentName”。

查詢如下 -

> db.distinctRecordDemo.distinct("StudentName");

以下是顯示 StudentName 不同記錄的輸出 -

[ "John", "Carol", "Sam", "Mike" ]

案例 2 - 這裡的欄位是“StudentAge”。

查詢如下 -

> db.distinctRecordDemo.distinct("StudentAge");

以下是顯示 StudentAge 不同記錄的輸出 -

[ 21, 22, 26, 24, 27, 28 ]

更新於: 2019 年 7 月 30 日

387 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告