Docs Menu
Docs Home
/
Start with Guides

Read Data in MongoDB

In this guide, you will learn how to retrieve data from MongoDB.

Time required: 10 minutes

  • A connection string to your MongoDB deployment.

  • Sample datasets loaded into your cluster.

  • An installed MongoDB Driver.

1

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to read data.

At line 5, replace the URI string with your own Atlas connection string.

CrudRead.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the uri string with your MongoDB deployment's connection string.
5var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7var client = new MongoClient(uri);
8
9// database and collection code goes here
10// find code goes here
11// iterate code goes here
12
13
14

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to read data.

At line 11, replace the URI string with your own Atlas connection string.

crudRead.go
1package main
2
3import (
4 "context"
5
6 "go.mongodb.org/mongo-driver/mongo"
7 "go.mongodb.org/mongo-driver/mongo/options"
8)
9
10func main() {
11 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
12
13 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
14 if err != nil {
15 panic(err)
16 }
17
18 defer func() {
19 if err = client.Disconnect(context.TODO()); err != nil {
20 panic(err)
21 }
22 }()
23
24 // database and colletion code goes here
25 // find code goes here
26 // iterate code goes here
27}

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to read data.

At line 8, replace the URI string with your own Atlas connection string.

CrudRead.java
1import com.mongodb.client.*;
2import com.mongodb.client.model.Filters.*;
3import org.bson.Document;
4import org.bson.conversions.Bson;
5
6public class CrudRead {
7 public static void main(String[] args) {
8 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
9
10 try (MongoClient mongoClient = MongoClients.create(uri)) {
11 // database and collection code goes here
12 // find code goes here
13 // iterate code goes here
14 }
15 }
16}

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to read data.

At line 4, replace the URI string with your own Atlas connection string.

crud-read.js
1const { MongoClient } = require("mongodb");
2// Replace the uri string with your MongoDB deployment's connection string.
3const uri =
4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
5const client = new MongoClient(uri);
6async function run() {
7 try {
8 await client.connect();
9 // database and collection code goes here
10 // find code goes here
11 // iterate code goes here
12 } finally {
13 // Ensures that the client will close when you finish/error
14 await client.close();
15 }
16}
17run().catch(console.dir);

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to read data.

At line 4, replace the URI string with your own Atlas connection string.

crud_read.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9# find code goes here
10# iterate code goes here
11
12# Close the connection to MongoDB when you're done.
13client.close()

Tip

mongodb+srv

Make sure you've installed PyMongo with the srv option.

python3 -m pip install "pymongo[srv]"

In this code block there is a comment to replace the connection URI with your own. Make sure to replace the URI string with your Atlas connection string.

2

Switch to the database and collection you want to query. In this case you will use the sample_guides database and planets collection.

CrudRead.cs
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<BsonDocument>("planets");
crudRead.go
1// database and colletion code goes here
2db := client.Database("sample_guides")
3coll := db.Collection("planets")
CrudRead.java
1// database and collection code goes here
2MongoDatabase db = mongoClient.getDatabase("sample_guides");
3MongoCollection<Document> coll = db.getCollection("planets");
crud-read.js
// database and collection code goes here
const db = client.db("sample_guides");
const coll = db.collection("planets");
crud_read.py
# database and collection code goes here
db = client.sample_guides
coll = db.planets
3
CrudRead.cs
// find code goes here
var cursor = coll.AsQueryable();

Use the Find() method to retrieve all documents. In another guide, you'll learn how to use the same method to retrieve documents that match specific criteria.

Tip

The empty bson.D{} is required to match all documents.

crudRead.go
1// find code goes here
2cursor, err := coll.Find(context.TODO(), bson.D{})
3if err != nil {
4 panic(err)
5}

Use the find() method to retrieve all documents. In another guide, you'll learn how to use the same method to retrieve documents that match specific criteria.

CrudRead.java
1// find code goes here
2MongoCursor<Document> cursor = coll.find().iterator();

Use the find() method to retrieve all documents. In another guide, you'll learn how to use the same method to retrieve documents that match specific criteria.

crud-read.js
// find code goes here
const cursor = coll.find();

Use the find() method to retrieve all documents. In another guide, you'll learn how to use the same method to retrieve documents that match specific criteria.

crud_read.py
# find code goes here
cursor = coll.find()
4
CrudRead.cs
// iterate code goes here
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}
crudRead.go
1// iterate code goes here
2for cursor.Next(context.TODO()) {
3 var result bson.M
4 if err := cursor.Decode(&result); err != nil {
5 panic(err)
6 }
7 fmt.Println(result)
8}
9if err := cursor.Err(); err != nil {
10 panic(err)
11}
CrudRead.java
1// iterate code goes here
2try {
3 while (cursor.hasNext()) {
4 System.out.println(cursor.next().toJson());
5 }
6} finally {
7 cursor.close();
8}

Iterate the results and print them to the console. Operations like this are asychronous in the MongoDB Node.js driver by default, meaning the Node.js runtime doesn't block other operations while waiting for them to finish execution.

In order to simplify the operation, you specify the await keyword, which will cause the runtime to wait for the operation. This is often easier than specifying a callback, or chaining a promise.

For more information, see the Promise and Callbacks guide.

crud-read.js
// iterate code goes here
await cursor.forEach(console.log);
crud_read.py
# iterate code goes here
for doc in cursor:
print(doc)
5

Here is the complete code followed by sample output.

Note

Your ObjectId values will differ from those shown.

Here is the complete code followed by sample output.

CrudRead.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the uri string with your MongoDB deployment's connection string.
5var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7var client = new MongoClient(uri);
8
9// database and collection code goes here
10var db = client.GetDatabase("sample_guides");
11var coll = db.GetCollection<BsonDocument>("planets");
12// find code goes here
13var cursor = coll.AsQueryable();
14// iterate code goes here
15foreach (var document in cursor)
16{
17 Console.WriteLine(document);
18}
19
20
{
'_id': ObjectId('621ff30d2a3e781873fcb65c'),
'name': 'Mercury',
'orderFromSun': 1,
'hasRings': False,
'mainAtmosphere': [],
'surfaceTemperatureC': {'min': -173, 'max': 427, 'mean': 67}
},
...

Here is the complete code followed by sample output.

crudRead.go
1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
14
15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
16 if err != nil {
17 panic(err)
18 }
19
20 defer func() {
21 if err = client.Disconnect(context.TODO()); err != nil {
22 panic(err)
23 }
24 }()
25
26 // database and colletion code goes here
27 db := client.Database("sample_guides")
28 coll := db.Collection("planets")
29
30 // find code goes here
31 cursor, err := coll.Find(context.TODO(), bson.D{})
32 if err != nil {
33 panic(err)
34 }
35
36 // iterate code goes here
37 for cursor.Next(context.TODO()) {
38 var result bson.M
39 if err := cursor.Decode(&result); err != nil {
40 panic(err)
41 }
42 fmt.Println(result)
43 }
44 if err := cursor.Err(); err != nil {
45 panic(err)
46 }
47
48}
map[_id:ObjectID("621ff30d2a3e781873fcb65c") hasRings:false mainAtmosphere:[] name:Mercury orderFromSun:1 surfaceTemperatureC:map[max:427 mean:67 min:-173]]
...

Here is the complete code followed by sample output.

CrudRead.java
1import com.mongodb.client.*;
2import com.mongodb.client.model.Filters.*;
3import org.bson.Document;
4import org.bson.conversions.Bson;
5
6public class CrudRead {
7 public static void main(String[] args) {
8 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
9
10 try (MongoClient mongoClient = MongoClients.create(uri)) {
11 // database and collection code goes here
12 MongoDatabase db = mongoClient.getDatabase("sample_guides");
13 MongoCollection<Document> coll = db.getCollection("planets");
14
15 // find code goes here
16 MongoCursor<Document> cursor = coll.find().iterator();
17
18 // iterate code goes here
19 try {
20 while (cursor.hasNext()) {
21 System.out.println(cursor.next().toJson());
22 }
23 } finally {
24 cursor.close();
25 }
26 }
27 }
28}
{"_id": {"$oid": "621ff30d2a3e781873fcb65c"}, "name": "Mercury", "orderFromSun": 1, "hasRings": false, "mainAtmosphere": [], "surfaceTemperatureC": {"min": -173, "max": 427, "mean": 67}}
...

Here is the complete code followed by sample output.

crud-read.js
1const { MongoClient } = require("mongodb");
2// Replace the uri string with your MongoDB deployment's connection string.
3const uri =
4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
5const client = new MongoClient(uri);
6async function run() {
7 try {
8 await client.connect();
9 // database and collection code goes here
10 const db = client.db("sample_guides");
11 const coll = db.collection("planets");
12
13 // find code goes here
14 const cursor = coll.find();
15
16 // iterate code goes here
17 await cursor.forEach(console.log);
18 } finally {
19 // Ensures that the client will close when you finish/error
20 await client.close();
21 }
22}
23run().catch(console.dir);
{
'_id': ObjectId('621ff30d2a3e781873fcb65c'),
'name': 'Mercury',
'orderFromSun': 1,
'hasRings': False,
'mainAtmosphere': [],
'surfaceTemperatureC': {'min': -173, 'max': 427, 'mean': 67}
},
...

Here is the complete code followed by sample output.

crud_read.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9db = client.sample_guides
10coll = db.planets
11# find code goes here
12cursor = coll.find({"hasRings": True})
13# iterate code goes here
14for doc in cursor:
15 print(doc)
16
17# Close the connection to MongoDB when you're done.
18client.close()
{
'_id': ObjectId('621ff30d2a3e781873fcb65c'),
'name': 'Mercury',
'orderFromSun': 1,
'hasRings': False,
'mainAtmosphere': [],
'surfaceTemperatureC': {'min': -173, 'max': 427, 'mean': 67}
},
...

If you successfully completed the procedure in this guide, you have retrieved data from MongoDB.

In the next guide, you'll learn how to retrieve data from MongoDB using criteria.

For other CRUD guides:

What's Next
Read Data from MongoDB With Queries
15 mins

Use a query to specify which documents to retrieve documents in MongoDB.

Start Guide
Chapter 2
CRUD
  • Add a MongoDB Driver
  • Read Data in MongoDB
  • Read Data from MongoDB With Queries
  • Read Data using Operators and Compound Queries
  • Insert Data into MongoDB
  • Update Data in MongoDB
  • Delete Data from MongoDB