如何在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" } }