如何從 MongoDB 陣列中獲取特定元素?


你可以使用 aggregate 框架從 MongoDB 陣列中獲取特定元素。為了理解這個概念,讓我們建立一個包含文件的集合。建立包含文件的集合的查詢如下 –

> db.getParticularElement.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","C","C++","MongoDB","MySQL","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee027559dd2396bcfbfb1")
}

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

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

以下是輸出 –

{
   "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"),
   "InstructorName" : "Larry",
   "InstructorTechnicalSubject" : [
      "Java",
      "C",
      "C++",
      "MongoDB",
      "MySQL",
      "SQL Server"
   ]
}

以下是獲取陣列中特定元素的查詢 –

> db.getParticularElement.aggregate([
   ... {
      ... $project:
      ... {
         ... ElementFromAnArray: 1,
         ... FourthElement: { $arrayElemAt: [ "$InstructorTechnicalSubject", 3] },
         ...
      ... }
   ... }
... ]);

以下是輸出 –

{ "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement" : "MongoDB" }

更新於: 2019 年 7 月 30 日

149 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告