MongoDB 查询以访问数组中的对象
要访问数组中的对象,请使用点表示法。让我们使用文档创建集合 -
> 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" ] } ] }
Advertisement