MongoDB - 查詢嵌入式文件?
要在 MongoDB 中查詢嵌入式文件,請使用 aggregate()。讓我們建立一個包含文件的集合 -
> db.demo705.insertOne( ... { ... _id:101, ... "Information": ... [ ... { ... "StudentName":"Chris", ... "StudentAge":21 ... }, ... { ... "StudentName":"David", ... "StudentAge":23 ... }, ... { ... "StudentName":"Bob", ... "StudentAge":20 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
藉助 find() 方法顯示集合中的所有文件 -
> db.demo705.find();
這將生成以下輸出 -
{ "_id" : 101, "Information" : [ { "StudentName" : "Chris", "StudentAge" : 21 }, { "StudentName" : "David", "StudentAge" : 23 }, { "StudentName" : "Bob", "StudentAge" : 20 } ] }
以下是如何在 MongoDB 中查詢嵌入式文件 -
> db.demo705.aggregate( ... { $unwind: '$Information' }, ... { $match: {'Information.StudentAge': {$gte: 21}}}, ... { $project: {Information: 1}} ... )
這將生成以下輸出 -
{ "_id" : 101, "Information" : { "StudentName" : "Chris", "StudentAge" : 21 } } { "_id" : 101, "Information" : { "StudentName" : "David", "StudentAge" : 23 } }
廣告