如何在 MongoDB 嵌入式文件中查詢某個元素?
為了查詢某個元素,在 MongoDB 中使用 $project。讓我們建立一個文件集合 -
> db.demo744.insertOne( ... { ... studentInformation: ... [ ... { ... studentName:"Robert", ... grade:"A" ... }, ... { ... studentName:"Bob", ... grade:"C" ... }, ... { ... studentName:"John", ... grade:"B" ... }, ... { ... studentName:"Sam", ... grade:"A" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ead928a57bb72a10bcf0684") }
使用 find() 方法從集合中顯示所有文件 -
> db.demo744.find();
這將生成以下輸出 -
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }
以下是查詢,用於在嵌入式文件中查詢某個元素 -
> db.demo744.aggregate( ... { $unwind: '$studentInformation' }, ... { $match: {'studentInformation.grade':"A"}}, ... { $project: {"studentInformation.studentName": 1}} ... )
這將生成以下輸出 -
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } } { "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }
廣告