在 MongoDB 中提取子数组值?
若要在 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 } ] }
广告