Read Data in MongoDB
Overview
In this guide, you will learn how to retrieve data from MongoDB.
Time required: 10 minutes
What You'll Need
A connection string to your MongoDB deployment.
Sample datasets loaded into your cluster.
Procedure
Connect to your MongoDB instance.
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.
1 using MongoDB.Bson;
2 using MongoDB.Driver;
3
4 // Replace the uri string with your MongoDB deployment's connection string.
5 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7 var 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.
1 package main 2 3 import ( 4 "context" 5 6 "go.mongodb.org/mongo-driver/mongo" 7 "go.mongodb.org/mongo-driver/mongo/options" 8 ) 9 10 func 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.
1 import com.mongodb.client.*; 2 import com.mongodb.client.model.Filters.*; 3 import org.bson.Document; 4 import org.bson.conversions.Bson; 5 6 public 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.
1 const { MongoClient } = require("mongodb"); 2 // Replace the uri string with your MongoDB deployment's connection string. 3 const uri = 4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 5 const client = new MongoClient(uri); 6 async 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 } 17 run().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.
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = 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. 13 client.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.
Get the database and collection.
Switch to the database and collection you want to query. In this case
you will use the sample_guides
database and planets
collection.
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<BsonDocument>("planets");
1 // database and colletion code goes here 2 db := client.Database("sample_guides") 3 coll := db.Collection("planets")
1 // database and collection code goes here 2 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 3 MongoCollection<Document> coll = db.getCollection("planets");
// database and collection code goes here const db = client.db("sample_guides"); const coll = db.collection("planets");
# database and collection code goes here db = client.sample_guides coll = db.planets
Retrieve all documents in the planets
collection.
// 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.
1 // find code goes here 2 cursor, err := coll.Find(context.TODO(), bson.D{}) 3 if 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.
1 // find code goes here 2 MongoCursor<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.
// 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.
# find code goes here cursor = coll.find()
Iterate over the results.
// iterate code goes here
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}
1 // iterate code goes here 2 for 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 } 9 if err := cursor.Err(); err != nil { 10 panic(err) 11 }
1 // iterate code goes here 2 try { 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.
// iterate code goes here await cursor.forEach(console.log);
# iterate code goes here for doc in cursor: print(doc)
Check your results.
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.
1 using MongoDB.Bson;
2 using MongoDB.Driver;
3
4 // Replace the uri string with your MongoDB deployment's connection string.
5 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7 var client = new MongoClient(uri);
8
9 // database and collection code goes here
10 var db = client.GetDatabase("sample_guides");
11 var coll = db.GetCollection<BsonDocument>("planets");
12 // find code goes here
13 var cursor = coll.AsQueryable();
14 // iterate code goes here
15 foreach (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.
1 package main 2 3 import ( 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 12 func 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.
1 import com.mongodb.client.*; 2 import com.mongodb.client.model.Filters.*; 3 import org.bson.Document; 4 import org.bson.conversions.Bson; 5 6 public 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.
1 const { MongoClient } = require("mongodb"); 2 // Replace the uri string with your MongoDB deployment's connection string. 3 const uri = 4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 5 const client = new MongoClient(uri); 6 async 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 } 23 run().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.
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = MongoClient(uri) 7 8 # database and collection code goes here 9 db = client.sample_guides 10 coll = db.planets 11 # find code goes here 12 cursor = coll.find({"hasRings": True}) 13 # iterate code goes here 14 for doc in cursor: 15 print(doc) 16 17 # Close the connection to MongoDB when you're done. 18 client.close()
{ '_id': ObjectId('621ff30d2a3e781873fcb65c'), 'name': 'Mercury', 'orderFromSun': 1, 'hasRings': False, 'mainAtmosphere': [], 'surfaceTemperatureC': {'min': -173, 'max': 427, 'mean': 67} }, ...
Summary
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.
See Also
The MongoDB C# Driver documentation.
The MongoDB Go Driver documentation.
The MongoDB Java(Sync) Driver documentation.
The MongoDB Node.js Driver documentation.
The PyMongo documentation.
For other CRUD guides:
Use a query to specify which documents to retrieve documents in MongoDB.