使用find()
连同$elemMatch获取数组值。首先让我们创建一个包含文档的集合-
> db.fetchingArrayValuesDemo.insertOne( ... { ... "StudentName": "David", ... "StudentDetails": [ ... { ... "FatherName": "Bob", ... "CountryName": "US", ... ... "Favourite": [ ... { ... "Teacher": "DAVID", ... "Subject": [ ... "MySQL", ... "MongoDB", ... "Java" ... ], ... "Marks": [ ... 50, ... 60, ... 65 ... ] ... } ... ] ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e06fc3425ddae1f53b621fa") } > db.fetchingArrayValuesDemo.insertOne( ... { ... "StudentName": "Robert", ... "StudentDetails": [ ... { ... "FatherName": "Sam", ... "CountryName": "AUS", ... ... "Favourite": [ ... { ... "Teacher": "MIKE", ... "Subject": [ ... "Python", ... "C", ... "C++" ... ], ... "Marks": [ ... 76, ... 89, ... 91 ... ] ... } ... ] ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e06fc6825ddae1f53b621fb") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.fetchingArrayValuesDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] } { "_id" : ObjectId("5e06fc6825ddae1f53b621fb"), "StudentName" : "Robert", "StudentDetails" : [ { "FatherName" : "Sam", "CountryName" : "AUS", "Favourite" : [ { "Teacher" : "MIKE", "Subject" : [ "Python", "C", "C++" ], "Marks" : [ 76, 89, 91 ] } ] } ] }
这是获取数组值的查询-
> db.fetchingArrayValuesDemo.find({ ... StudentDetails:{ ... $elemMatch: { ... Favourite: { ... $elemMatch: { ... Teacher: "DAVID" ... } ... } ... } ... } ... });
这将产生以下输出-
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] }