要在MongoDB中提取子数组值,可以使用$elemMatch投影运算符。
首先让我们创建一个包含文档的集合-
> db.extractSubArrayDemo.insertOne( ... { ... _id: 101, ... "clientName":"Larry", ... "ClientDetails": ... [ ... { ... "ClientProjectName":"Online Game", ... "DeveloperTeamSize": 10 ... }, ... { ... "ClientProjectName":"Pig Dice Game", ... "DeveloperTeamSize": 12 ... }, ... { ... "ClientProjectName":"Web Student Tracker", ... "DeveloperTeamSize": 11 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.extractSubArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "clientName" : "Larry", "ClientDetails" : [ { "ClientProjectName" : "Online Game", "DeveloperTeamSize" : 10 }, { "ClientProjectName" : "Pig Dice Game", "DeveloperTeamSize" : 12 }, { "ClientProjectName" : "Web Student Tracker", "DeveloperTeamSize" : 11 } ] }
以下是在MongoDB中提取子数组值的查询-
> db.extractSubArrayDemo.find({ '_id': 101 },{ _id: 0, ClientDetails: { $elemMatch: {ClientProjectName: 'Pig Dice Game' } }}).pretty();
这将产生以下输出-
{ "ClientDetails" : [ { "ClientProjectName" : "Pig Dice Game", "DeveloperTeamSize" : 12 } ] }