要通过_id在对象数组上查找,请使用汇总,并避免使用find()
。首先让我们创建一个包含文档的集合-
> db.demo414.insertOne( ... { ... "_id": "110", ... "details":[ ... { ... "StudentName":"John", ... "StudentMarks":56 ... }, ... { ... "StudentName":"Robert", ... "StudentMarks":98 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "110" }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo414.find();
这将产生以下输出-
{ "_id" : "110", "details" : [ { "StudentName" : "John", "StudentMarks" : 56 }, { "StudentName" : "Robert", "StudentMarks" : 98 } ] }
以下是通过_id在对象数组上查找的查询-
> db.demo414.aggregate([{$unwind: "$details"}, {$match:{"details.StudentMarks" :56}}] )
这将产生以下输出-
{ "_id" : "110", "details" : { "StudentName" : "John", "StudentMarks" : 56 } }