要访问MongoDB中的子文档,请使用find()
点符号。让我们创建一个包含文档的集合-
> db.demo670.insertOne({ ... id:101, ... "details": ... { ... Name:"Chris", ... Age:21, ... CountryName:"US", ... SubjectName:"MongoDB" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e31d04263e90dac943de") } > db.demo670.insertOne({ id:102, "details": { Name:"David", Age:22, CountryName:"UK", SubjectName:"MySQL" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ea3e33604263e90dac943df") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo670.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "id" : 101, "details" : { "Name" : "Chris", "Age" : 21, "CountryName" : "US", "SubjectName" : "MongoDB" } } { "_id" : ObjectId("5ea3e33604263e90dac943df"), "id" : 102, "details" : { "Name" : "David", "Age" : 22, "CountryName" : "UK", "SubjectName" : "MySQL" } }
以下是访问子文档的查询-
> db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});7
这将产生以下输出-
{ "_id" : ObjectId("5ea3e31d04263e90dac943de"), "details" : { "CountryName" : "US" } }