要访问数组中的对象,请使用点表示法。让我们创建一个包含文档的集合-
> db.demo299.insertOne( ... { ... "id":100, ... "Name":"Robert", ... "details":[ ... { ... "SubjectName":["C++","Python"] ... }, ... { ... "SubjectName":["Spring","Hibernate"] ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4d685a5d93261e4bc9ea4b") } > > > db.demo299.insertOne( ... { ... "id":101, ... "Name":"Adam", ... "details":[ ... { ... "SubjectName":["Python","JSP"] ... }, ... { ... "SubjectName":["Servlet","Operating System"] ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e4d685b5d93261e4bc9ea4c") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo299.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4d685a5d93261e4bc9ea4b"), "id" : 100, "Name" : "Robert", "details" : [ { "SubjectName" : [ "C++", "Python" ] }, { "SubjectName" : [ "Spring", "Hibernate" ] } ] } { "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [ { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] } ] }
以下是访问数组中对象的查询-
> db.demo299.find({"details.SubjectName":"Servlet"});
这将产生以下输出-
{ "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [ { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] } ] }