是的,您可以使用findOne()
。以下是语法-
db.yourCollectionName.findOne();
您也可以使用toArray()
-
db.yourCollectionName.find().toArray();
首先让我们创建一个包含文档的集合-
> db.betterFormatDemo.insertOne({"StudentName":"Adam Smith","StudentScores":[98,67,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ab826d78f205348bc640") } > db.betterFormatDemo.insertOne({"StudentName":"John Doe","StudentScores":[67,89,56]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ab936d78f205348bc641") } > db.betterFormatDemo.insertOne({"StudentName":"Sam Williams","StudentScores":[45,43,33]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7aba76d78f205348bc642") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.betterFormatDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] } { "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] } { "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] }
情况1-使用findOne()
。
以下是查询以更好的格式显示MongoDB结果-
> db.betterFormatDemo.findOne();
这将产生以下输出-
{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }
情况2-使用find()
.toArray()。
以下是查询以更好的格式显示MongoDB结果-
> db.betterFormatDemo.find().toArray();
这将产生以下输出-
[ { "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }, { "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] }, { "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] } ]