查询 MongoDB 中子文档的数组
要查询子文档的数组,需要在 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" } }
广告