在 MongoDB 資料庫中按陣列中的 _id 來查詢?


若要按陣列中的 _id 查詢,請使用聚合並避免使用 find()。我們先使用文件建立集合 -

> db.demo414.insertOne(
...    {
...       "_id": "110",
...       "details":[
...          {
...             "StudentName":"John",
...             "StudentMarks":56
...          },
...          {
...             "StudentName":"Robert",
...             "StudentMarks":98
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : "110" }

藉助 find() 方法顯示集合中的所有文件 -

> db.demo414.find();

這將產生以下輸出 -

{ "_id" : "110", "details" : [ { "StudentName" : "John", "StudentMarks" : 56 }, { "StudentName" : "Robert", "StudentMarks" : 98 } ] }

以下是按陣列中的 _id 查詢的查詢 -

> db.demo414.aggregate([{$unwind: "$details"}, {$match:{"details.StudentMarks" :56}}] )

這將產生以下輸出 -

{ "_id" : "110", "details" : { "StudentName" : "John", "StudentMarks" : 56 } }

更新於:2020 年 4 月 3 日

已檢視 746 次

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告