要访问文档中的字段,只需使用find()
。让我们创建一个包含文档的集合-
> db.demo565.insertOne( ... { ... id:101, ... Name:"David", ... "CountryName":"US" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e90896739cfeaaf0b97b577") } > > db.demo565.insertOne( ... { ... id:102, ... Name:"Carol", ... "CountryName":"UK" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e90896839cfeaaf0b97b578") } > > db.demo565.insertOne( ... { ... id:103, ... Name:"Sam", ... "CountryName":"AUS" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e90896839cfeaaf0b97b579") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo565.find();
这将产生以下输出-
{ "_id" : ObjectId("5e90896739cfeaaf0b97b577"), "id" : 101, "Name" : "David", "CountryName" : "US" } { "_id" : ObjectId("5e90896839cfeaaf0b97b578"), "id" : 102, "Name" : "Carol", "CountryName" : "UK" } { "_id" : ObjectId("5e90896839cfeaaf0b97b579"), "id" : 103, "Name" : "Sam", "CountryName" : "AUS" }
以下是访问字段的查询-
> db.demo565.find({"Name":"Carol",CountryName:"UK"},{Name:1});
这将产生以下输出-
{ "_id" : ObjectId("5e90896839cfeaaf0b97b578"), "Name" : "Carol" }