当键是MongoDB中的数字时,如何访问子文档值?
要访问子文档的值,让我们首先创建一个包含文档的集合-
> 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" }