如何在MongoDB中检索集合中的文档?
要从MongoDB中的集合中检索文档,您需要使用find()方法。语法如下:
db.yourCollectionName.find();
以上语法将返回MongoDB中集合中的所有文档。为了理解以上语法,让我们创建一个包含文档的集合。创建文档的查询如下:
> db.retrieveAllStudents.insertOne({"StudentId":"STUD101","StudentName":"David","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c6bf5cf68174aae23f5ef4e") } > db.retrieveAllStudents.insertOne({"StudentId":"STUD102","StudentName":"Carol","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c6bf5e968174aae23f5ef4f") } > db.retrieveAllStudents.insertOne({"StudentId":"STUD103","StudentName":"Maxwell","StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c6bf5f768174aae23f5ef50") } > db.retrieveAllStudents.insertOne({"StudentId":"STUD104","StudentName":"Bob","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c6bf60868174aae23f5ef51") } > db.retrieveAllStudents.insertOne({"StudentId":"STUD105","StudentName":"Sam","StudentAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c6bf61b68174aae23f5ef52") }
现在您可以使用以上语法,借助find()方法检索集合中的所有文档。查询如下:
> db.retrieveAllStudents.find();
以下是输出结果:
{ "_id" : ObjectId("5c6bf5cf68174aae23f5ef4e"), "StudentId" : "STUD-101", "StudentName" : "David", "StudentAge" : 24 } { "_id" : ObjectId("5c6bf5e968174aae23f5ef4f"), "StudentId" : "STUD-102", "StudentName" : "Carol", "StudentAge" : 22 } { "_id" : ObjectId("5c6bf5f768174aae23f5ef50"), "StudentId" : "STUD-103", "StudentName" : "Maxwell", "StudentAge" : 25 } { "_id" : ObjectId("5c6bf60868174aae23f5ef51"), "StudentId" : "STUD-104", "StudentName" : "Bob", "StudentAge" : 23 } { "_id" : ObjectId("5c6bf61b68174aae23f5ef52"), "StudentId" : "STUD-105", "StudentName" : "Sam", "StudentAge" : 27 }
为了获得格式良好的输出,请将pretty()与find()一起使用。查询如下:
> db.retriveAllStudents.find().pretty();
以下是输出结果:
{ "_id" : ObjectId("5c6bf5cf68174aae23f5ef4e"), "StudentId" : "STUD-101", "StudentName" : "David", "StudentAge" : 24 } { "_id" : ObjectId("5c6bf5e968174aae23f5ef4f"), "StudentId" : "STUD-102", "StudentName" : "Carol", "StudentAge" : 22 } { "_id" : ObjectId("5c6bf5f768174aae23f5ef50"), "StudentId" : "STUD-103", "StudentName" : "Maxwell", "StudentAge" : 25 } { "_id" : ObjectId("5c6bf60868174aae23f5ef51"), "StudentId" : "STUD-104", "StudentName" : "Bob", "StudentAge" : 23 } { "_id" : ObjectId("5c6bf61b68174aae23f5ef52"), "StudentId" : "STUD-105", "StudentName" : "Sam", "StudentAge" : 27 }
如果您想根据某些条件检索单个文档,则可以使用以下查询。这里,我们正在检索StudentName为“Maxwell”的文档。
> db.retriveAllStudents.find({"StudentName":"Maxwell"}).pretty();
以下是输出结果:
{ "_id" : ObjectId("5c6bf5f768174aae23f5ef50"), "StudentId" : "STUD-103", "StudentName" : "Maxwell", "StudentAge" : 25 }
广告