Click the link: "MongoDB - Query Document"
In this MongoDB tutorial we will learn to query documents.
Select all the documents
To select all the documents in a collection we use the
find()
method.
In the following example we are listing all the documents in the students collection.
> db.students.find();
{ "_id" : ObjectId("5d16c9e9e8cb73839ac9f2f1"), "firstname" : "Yusuf", "lastname" : "Shakeel", "studentid" : "s01" }
{ "_id" : ObjectId("5d16c9efe8cb73839ac9f2f2"), "firstname" : "Jane", "lastname" : "Doe", "studentid" : "s02" }
{ "_id" : ObjectId("5d16c9efe8cb73839ac9f2f3"), "firstname" : "John", "lastname" : "Doe", "studentid" : "s03" }
{ "_id" : ObjectId("5d16ca23e8cb73839ac9f2f4"), "firstname" : "Alice", "lastname" : "Doe", "studentid" : "s04", "score" : 10.5 }
{ "_id" : ObjectId("5d16ca23e8cb73839ac9f2f5"), "firstname" : "Bob", "lastname" : "Doe", "studentid" : "s05", "date_of_birth" : ISODate("2000-01-01T00:00:00Z") }
{ "_id" : ObjectId("5d16cfa4e8cb73839ac9f2f6"), "firstname" : "Eve", "lastname" : "Doe", "studentid" : "s06", "contact_phone" : { "primary" : { "number" : "+919800000000", "name" : "Bill Doe", "relation" : "Father" }, "secondary" : [ { "number" : "+919800000001", "name" : "Mac Doe", "relation" : "Brother" } ] } }
Select all documents and render in easy-to-read format
To render the result in easy to read format we use the
pretty()
method.
In the following example we are selecting all the documents in the students collection and listing them in an easy-to-read format.
> db.students.find().pretty();
{
"_id" : ObjectId("5d16c9e9e8cb73839ac9f2f1"),
"firstname" : "Yusuf",
"lastname" : "Shakeel",
"studentid" : "s01"
}
{
"_id" : ObjectId("5d16c9efe8cb73839ac9f2f2"),
"firstname" : "Jane",
"lastname" : "Doe",
"studentid" : "s02"
}
{
"_id" : ObjectId("5d16c9efe8cb73839ac9f2f3"),
"firstname" : "John",
"lastname" : "Doe",
"studentid" : "s03"
}
{
"_id" : ObjectId("5d16ca23e8cb73839ac9f2f4"),
"firstname" : "Alice",
"lastname" : "Doe",
"studentid" : "s04",
"score" : 10.5
}
{
"_id" : ObjectId("5d16ca23e8cb73839ac9f2f5"),
"firstname" : "Bob",
"lastname" : "Doe",
"studentid" : "s05",
"date_of_birth" : ISODate("2000-01-01T00:00:00Z")
}
{
"_id" : ObjectId("5d16cfa4e8cb73839ac9f2f6"),
"firstname" : "Eve",
"lastname" : "Doe",
"studentid" : "s06",
"contact_phone" : {
"primary" : {
"number" : "+919800000000",
"name" : "Bill Doe",
"relation" : "Father"
},
"secondary" : [
{
"number" : "+919800000001",
"name" : "Mac Doe",
"relation" : "Brother"
}
]
}
}
The
find()
method is equivalent to the following SQL statement.SELECT * FROM students;
No comments:
Post a Comment