要从数组中获取特定值,请使用aggregate()和$project。让我们创建一个包含文档的集合-
> db.demo761.insertOne( ... { ... "details": [ ... { ... "student": { ... "FullName": "Chris Brown" ... } ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb034d15637cd592b2a4af1") } > db.demo761.insertOne( ... { ... "details": [ ... { ... "student": { ... "FullName": "Chris Taylor" ... } ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb034d25637cd592b2a4af2") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo761.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb034d15637cd592b2a4af1"), "details" : [ { "student" : { "FullName" : "Chris Brown" } } ] } { "_id" : ObjectId("5eb034d25637cd592b2a4af2"), "details" : [ { "student" : { "FullName" : "Chris Taylor" } } ] }
以下是如何在MongoDB中查询数组-
> db.demo761.aggregate([ ... {'$unwind':'$details'}, ... {'$match': { ... 'details.student.FullName':'Chris Taylor', ... }}, ... {'$project': { ... 'details.student.FullName': 1, '_id': 0 ... }}, ... ])
这将产生以下输出-
{ "details" : { "student" : { "FullName" : "Chris Taylor" } } }