从 MongoDB 的嵌套数组中提取特定元素
使用点(.)表示法从嵌套数组中提取特定元素。我们首先使用文档创建集合 −
> db.extractParticularElementDemo.insertOne(
... {
... "_id" : 101,
... "StudentName" : "John",
... "StudentInformation" : [
... {
... "Age" : 21,
... "StudentPersonalInformation" : [
... {
... "StudentNickName" : "Mike",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Carol"
... }
... ]
... },
... {
... "StudentAnotherName" : "David",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Robert"
... }
... ]
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.extractParticularElementDemo.find().pretty();
这将产生以下输出 −
{
"_id" : 101,
"StudentName" : "John",
"StudentInformation" : [
{
"Age" : 21,
"StudentPersonalInformation" : [
{
"StudentNickName" : "Mike",
"StudentFamilyDetails" : [
{
"FatherName" : "Carol"
}
]
},
{
"StudentAnotherName" : "David",
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}以下是用于从嵌套数组中提取特定元素的查询 −
> db.extractParticularElementDemo.find(
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'},
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0}
... ).pretty();这将产生以下输出 −
{
"StudentInformation" : [
{
"StudentPersonalInformation" : [
{
"StudentFamilyDetails" : [
{
}
"FatherName" : "Carol"
]
},
{
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP