如何在嵌套数组中提取 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" } ] } ] } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP