要查询子文档数组,请在MongoDB中使用$unwind。让我们创建一个包含文档的集合-
> db.demo499.insertOne({ ... "details": ... [ ... { ... Name :"MIT", ... Rank: 1, ... "CountryName":"US" ... }, ... ... { ... Name :"Stanford University", ... Rank: 2 ... }, ... ... { ... Name :"University of California, Berkeley", ... Rank: 3 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e87433d987b6e0e9d18f558") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo499.find();
这将产生以下输出-
{ "_id" : ObjectId("5e87433d987b6e0e9d18f558"), "details" : [ { "Name" : "MIT", "Rank" : 1, "CountryName" : "US" }, { "Name" : "Stanford University", "Rank" : 2 }, { "Name" : "University of California, Berkeley", "Rank" : 3 } ] }
以下是如何查询子文档数组-
> db.demo499.aggregate({$unwind: "$details"}, ... {$match: {"details.CountryName":{$exists: true}}}, ... {$project: {"details.Name": 1, "details.CountryName": 1, "_id": 0}})
这将产生以下输出-
{ "details" : { "Name" : "MIT", "CountryName" : "US" } }