要获取MongoDB中嵌套JSON对象的数据,请使用findOne()
。让我们创建一个包含文档的集合-
> db.demo109.insertOne( ... { ... "Name" : "Chris", ... "Subjects" : [ ... { ... "Id" : "100", ... "Name":"MySQL", ... "InstructorDetails" : [ ... { ... "Name" : "John" ... } ... ] ... }, ... { ... "Id" : "101", ... "Name":"MongoDB", ... "InstructorDetails" : [ ... { ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee7df9fd5fd66da21447a") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo109.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Name" : "Chris", "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] }, { "Id" : "101", "Name" : "MongoDB", "InstructorDetails" : [ { "Name" : "Mike" } ] } ] }
以下是仅获取MongoDB中嵌套JSON对象的数据的查询-
> db.demo109.findOne( ... { Name: "Chris"} ... , { 'Subjects': { $elemMatch:{'Id':"100"} } } ... , function (err, doc) { console.log(doc) });
这将产生以下输出-
{ "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] } ] }