要从集合中返回单个文档,请findOne()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo463.insertOne({"StudentName":"Chris Brown","StudentAge":21,"StudentCountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ec8cb66ccba22cc9dcf") } > db.demo463.insertOne({"StudentName":"David Miller","StudentAge":23,"StudentCountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ed5cb66ccba22cc9dd0") } > db.demo463.insertOne({"StudentName":"John Doe","StudentAge":22,"StudentCountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ee1cb66ccba22cc9dd1") } > db.demo463.insertOne({"StudentName":"John Smith","StudentAge":24,"StudentCountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7eefcb66ccba22cc9dd2") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo463.find();
这将产生以下输出-
{ "_id" : ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName" : "Chris Brown", "StudentAge" : 21, "StudentCountryName" : "US" } { "_id" : ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName" : "David Miller", "StudentAge" : 23, "StudentCountryName" : "UK" } { "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" : 22, "StudentCountryName" : "AUS" } { "_id" : ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName" : "John Smith", "StudentAge" : 24, "StudentCountryName" : "US" }
以下是从MongoDB检索数据的查询-
> db.demo463.findOne({"StudentName":"John Doe"});
这将产生以下输出-
{ "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" : 22, "StudentCountryName" : "AUS" }