要查询对象数组中的嵌套文档,请使用find()。让我们创建一个包含文档的集合-
> db.demo763.insertOne(
... {
... _id:1,
... CountryName:"US",
... "studentInformation": [
... {
... StudentName:"Chris",
... },
... {
... StudentName:"David",
... StudentAge:22
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }在find()方法的帮助下显示集合中的所有文档-
> db.demo763.find();
这将产生以下输出-
{ "_id" : 1, "CountryName" : "US", "studentInformation" : [ { "StudentName" : "Chris" }, { "StudentName" : "David", "StudentAge" : 22 } ] }以下是如何查询对象数组以获取特定的嵌套文档-
> db.demo763.find({},
... {
... studentInformation: {
... $elemMatch: {
... StudentAge: {
... $exists: true
... }
... }
... }
... })这将产生以下输出-
{ "_id" : 1, "studentInformation" : [ { "StudentName" : "David", "StudentAge" : 22 } ] }