在 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 } }
廣告