当 MongoDB 中的键是数字时,如何访问子文档的值?
mongodbdatabasebig data analytics更新于 2026/2/16 1:07:17
要访问子文档的值,我们首先创建一个包含文档的集合。 −
> db.accessSubDocumentDemo.insertOne(
... {
...
... "Details" : {
... "1" : {
... "StudentLowerScore" : "33",
... "StudentHoghScore" : "55"
... },
... "2" : {
... "StudentLowerScore" : "45",
... "StudentHoghScore" : "65"
... },
... "3" : {
... "StudentLowerScore" : "39",
... "StudentHoghScore" : "91"
... },
... "4" : {
... "StudentLowerScore" : "41",
... "StudentHoghScore" : "85"
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3baf0edc6604c74817cd6")
}
以下是使用 find() 方法显示集合中的所有文档的查询 −
> db.accessSubDocumentDemo.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5cd3baf0edc6604c74817cd6"),
"Details" : {
"1" : {
"StudentLowerScore" : "33",
"StudentHoghScore" : "55"
},
"2" : {
"StudentLowerScore" : "45",
"StudentHoghScore" : "65"
},
"3" : {
"StudentLowerScore" : "39",
"StudentHoghScore" : "91"
},
"4" : {
"StudentLowerScore" : "41",
"StudentHoghScore" : "85"
}
}
}
现在,当键是数字时,我们将访问子文档值:这里,使用数字 1 的键访问子文档−
> db.accessSubDocumentDemo.findOne().Details["1"];
这将产生以下输出 −
{ "StudentLowerScore" : "33", "StudentHoghScore" : "55" }

