在嵌套数组中提取MongoDB中的特定元素?
要提取MongoDB中的特定元素,可以使用$elemMatch运算符。首先让我们创建一个包含文档的集合-
> db.particularElementDemo.insertOne( { "GroupId" :"Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "John123@gmail.com", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "John22@hotmail.com", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] } ); { "acknowledged" : true, "insertedId" : 100 } > db.particularElementDemo.find().pretty(); { "_id" : 100, "GroupId" : "Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "John123@gmail.com", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "John22@hotmail.com", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }
在find()
方法的帮助下显示集合中的所有文档-
> db.particularElementDemo.find().pretty();
这将产生以下输出-
{ "_id" : 100, "GroupId" : "Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "John123@gmail.com", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "John22@hotmail.com", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }
以下是在嵌套数组中提取MongoDB中特定元素的查询-
> db.particularElementDemo.find( { 'UserDetails':{ $elemMatch:{ 'UserOtherDetails':{ $elemMatch:{ 'UserFriendName':{ $elemMatch: {"Name" : "Robert" } } } } } } },{"UserDetails.UserOtherDetails.UserFriendName.Name":1} );
这将产生以下输出-
{ "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }