如何从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()
method来从集合中检索所有文档。查询如下:
> 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 }