要进行过滤和获取,请使用投影以及MongoDB $filter和$match。让我们创建一个包含文档的集合-
> db.demo507.insertOne( ... { ... ... "Information": ... [ ... {"Name":"John","SubjectName":"MySQL"}, ... {"Name":"Bob","SubjectName":"MongoDB"}, ... {"Name":"Chris","SubjectName":"MySQL"}, ... {"Name":"David","SubjectName":"C++"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8836d3987b6e0e9d18f577") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo507.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e8836d3987b6e0e9d18f577"), "Information" : [ { "Name" : "John", "SubjectName" : "MySQL" }, { "Name" : "Bob", "SubjectName" : "MongoDB" }, { "Name" : "Chris", "SubjectName" : "MySQL" }, { "Name" : "David", "SubjectName" : "C++" } ] }
以下是用于过滤对象中某些字段的查询-
> db.demo507.aggregate([ ... {$match: {"Information.SubjectName" : "MySQL" } }, ... {$project: { ... _id:0, ... Information: { ... $filter: { ... input: '$Information', ... as: 'result', ... cond: {$eq: ['$$result.SubjectName', 'MySQL']} ... } ... } ... } ... },{$project: {Information: { SubjectName:1}}} ... ]);
这将产生以下输出-
{ "Information" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MySQL" } ] }