您可以使用$match。$match过滤文档以仅将符合指定条件的文档传递到下一个管道阶段。让我们创建一个包含文档的集合-
> db.demo629.insertOne( ... { ... ... "Subject": [ ... "MySQL", ... "MongoDB" ... ], ... "details": [ ... { ... Name:"Chris", ... "Marks":78 ... }, ... { Name:"David", ... "Marks":89 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae9f56c954c74be91e6b9") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo629.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9ae9f56c954c74be91e6b9"), "Subject" : [ "MySQL", "MongoDB" ], "details" : [ { "Name" : "Chris", "Marks" : 78 }, { "Name" : "David", "Marks" : 89 } ] }
以下是使用简单查询在MongoDB中过滤文档的查询-
> db.demo629.aggregate([ ... {"$unwind": "$details"}, ... {"$match": {"details.Name": 'Chris', "Subject": {"$in":["Java","MySQL","Python","C","C++"]}}}, ... {"$project": {"details": 1, "_id": 0}} ... ]);
这将产生以下输出-
{ "details" : { "Name" : "Chris", "Marks" : 78 } }