要检索集合中的第一个文档,可以使用findOne()
。以下是语法
var anyVariableName=db.yourCollectionName.findOne(); //要在MongoDB控制台上打印结果,请写入变量名称 yourVariableName
首先让我们创建一个包含文档的集合
> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2325966324ffac2a7dc6d") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2326266324ffac2a7dc6e") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2327566324ffac2a7dc70") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.retrieveFirstDocumentDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca2325966324ffac2a7dc6d"), "ClientName" : "Robert", "ClientAge" : 23 } { "_id" : ObjectId("5ca2326266324ffac2a7dc6e"), "ClientName" : "Chris", "ClientAge" : 26 } { "_id" : ObjectId("5ca2326a66324ffac2a7dc6f"), "ClientName" : "Larry", "ClientAge" : 29 } { "_id" : ObjectId("5ca2327566324ffac2a7dc70"), "ClientName" : "David", "ClientAge" : 39 }
以下是检索集合中第一个文档的查询
> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne(); > firstDocumentOnly;
这将产生以下输出
{ "_id" : ObjectId("5ca2325966324ffac2a7dc6d"), "ClientName" : "Robert", "ClientAge" : 23 }