MongoDB 中是否支持获取 JSON 数据的内部值?


要获取 JSON 数据的内部值,请使用 find() 与点号(.)表示法。让我们使用文档创建一个集合 −

> db.demo235.insertOne(
...   {
...      "id":101,
...      "details":[
...         {
...            "Name":"Chris Brown",
...            "Age":21
...         },
...         {
...            "Name":"David Miller",
...            "Age":24
...         }
...      ],
...      "otherdetails":[
...         {
...            "Score":56,
...            "Subject":"MongoDB"
...         },
...         {
...            "Score":78,
...            "Subject":"MySQL"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e418d22f4cebbeaebec514b")
}

使用 find() 方法显示集合中的所有文档 −

> db.demo235.find().pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5e418d22f4cebbeaebec514b"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris Brown",
         "Age" : 21
      },
      {
         "Name" : "David Miller",
         "Age" : 24
      }
   ],
   "otherdetails" : [
      {
         "Score" : 56,
         "Subject" : "MongoDB"
      },
      {
         "Score" : 78,
         "Subject" : "MySQL"
      }
   ]
}

以下是获取 JSON 数据内部值时使用的查询 −

> db.demo235.find({},{"otherdetails.Subject":1,_id:0});

这将产生以下输出 −

{ "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }

更新于: 2020 年 3 月 30 日

146 次浏览

开启你的 职业生涯

完成课程,获取认证

开始学习
广告
© . All rights reserved.