当键为 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" }
广告