Insert and View a Document
Estimated completion time: 5 minutes
After you've connected to your Atlas cluster,
you can interact with it. In this tutorial, you insert
data into your cluster and read the new data by using mongosh
,
the Atlas UI, MongoDB Compass,
or a supported MongoDB driver.
➤ Use the Select your language drop-down menu to set the method for this tutorial.
Required Access
To interact with a cluster, you must be a database user.
Prerequisites
Before you start, you must configure your preferred connection method. To learn more, see Connect to Your Cluster.
Insert and View Data
Atlas provides a GUI to interact with data in your cluster.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
Insert documents into the collection.
Select the
people
collection if it's not selected.Click Insert Document.
Click the JSON view ({}) to replace the default document.
Paste the following code:
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } Click Insert to add the document.
Click Insert Document.
Click the JSON view ({}) to replace the default document.
Paste the following code:
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } Click Insert to add the document.
View the document.
Click Apply to run the query and view the document that you inserted. You should see the following document in your query results:
_id: ObjectId('64d52c3c3db2144fc00791b9'}, name: Object first: "Alan" last: "Turing" birth: 1912-06-23T06:00:00.000+00:00 death: 1954-06-07T05:00:00.000+00:00 contribs: Array 0: "Turing machine" 1: "Turing test" 2: "Turingery" views: 1250000
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more, see Create, View, Update, and Delete Documents.
Insert documents into your database.
In mongosh
, run the following command to insert
documents into your new database:
db.people.insertMany([ { name: { first: 'Alan', last: 'Turing' }, birth: new Date('Jun 23, 1912'), death: new Date('Jun 07, 1954'), contribs: [ 'Turing machine', 'Turing test', 'Turingery' ], views : Long(1250000) }, { name: { first: 'Grace', last: 'Hopper' }, birth: new Date('Dec 9, 1906'), death: new Date('Jan 1, 1992'), contribs: [ 'Mark I', 'UNIVAC', 'COBOL' ], views : Long(3860000) }] );
{ acknowledged: true, insertedIds: { '0': ObjectId('65c28946edcfbff3c7ce90c4'), '1': ObjectId('65c28946edcfbff3c7ce90c5') } }
Note
You might see a different value for ObjectId, because it is a system-generated value.
This command creates a new collection in your
gettingStarted
database called people
and inserts one
document into that collection.
View a document.
To view one of the documents that you just inserted into your
cluster, run the following command to search the
people
collection for documents that have a
name.last
value of Turing
:
db.people.find({ "name.last": "Turing" })
{ _id: ObjectId("65c28946edcfbff3c7ce90c4"), name: { first: 'Alan', last: 'Turing' }, birth: ISODate("1912-06-23T04:00:00Z"), death: ISODate("1954-06-07T04:00:00Z"), contribs: [ 'Turing machine', 'Turing test', 'Turingery' ], views: Long("1250000") }
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data in MongoDB, see Query Documents.
Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.
Insert documents into the collection.
In the left navigation, click the
gettingStarted
database.Select the
people
collection.In the Documents tab for the collection, click Add Data.
Click Insert Document and paste the following code:
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } Click Insert to add the document.
In the Documents tab for the collection, click Add Data.
Click Insert Document and paste the following code:
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } Click Insert to add the document.
View the document.
Click Find to run the query and view the document that you inserted. You should see the following document in your query results:
_id: ObjectId('65c28c938dfecbc5fb1bd220'}, name: Object first: "Alan" last: "Turing" birth: 1912-06-23T06:00:00.000+00:00 death: 1954-06-07T05:00:00.000+00:00 contribs: Array 0: "Turing machine" 1: "Turing test" 2: "Turingery" views: 1250000
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more, see the Compass documentation.
The following sample application:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Inserts documents into a collection called
people
in thegettingStarted
database.Searches the
people
collection for documents that have aname.last
value ofTuring
and returns the document.
In your .NET/C# project with the driver and dependencies
installed, copy the following code into the Program.cs
file:
Note
Replace the placeholder with your Atlas connection string.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 6 public class InsertData 7 { 8 // Replace the following with your Atlas connection string 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // Connect to your Atlas cluster 14 var client = new MongoClient(MongoConnectionString); 15 16 // Reference the database and collection to use 17 var database = client.GetDatabase("gettingStarted"); 18 var peopleCollection = database.GetCollection<Person>("people"); 19 20 // Create new documents 21 var newPerson = new List<Person>() { 22 new Person { 23 Name = new Name { First = "Alan", Last = "Turing" }, 24 Birth = new DateTime(1912, 5, 23), // May 23, 1912 25 Death = new DateTime(1954, 5, 7), // May 7, 1954 26 Contribs = new string[] {"Turing machine", "Turing test", "Turingery"}, 27 Views = 1250000 28 },new Person { 29 Name = new Name { First = "Grace", Last = "Hopper" }, 30 Birth = new DateTime(1906, 12, 9), // Dec 9, 1906 31 Death = new DateTime(1992, 1, 1), // Jan 1, 1992 32 Contribs = new string[] {"Mark I", "UNIVAC", "COBOL"}, 33 Views = 3860000 34 } 35 }; 36 37 // Insert the documents into the specified collection 38 peopleCollection.InsertMany(newPerson); 39 40 // Find the document 41 var filter = Builders<Person>.Filter 42 .Eq(person => person.Name.Last, "Turing"); 43 44 var document = peopleCollection.Find(filter).FirstOrDefault(); 45 46 // Print the result 47 Console.WriteLine($"Document found:\n{document.ToBsonDocument()}"); 48 } 49 } 50 51 public class Person 52 { 53 public ObjectId Id { get; set; } 54 public Name Name { get; set; } 55 public DateTime Birth { get; set; } 56 public DateTime Death { get; set; } 57 public string[] Contribs { get; set; } 58 public int Views { get; set; } 59 } 60 public class Name 61 { 62 public string First { get; set; } 63 public string Last { get; set; } 64 }
To run the sample application, use the following command:
dotnet run Program.cs
Document found: { "_id" : ObjectId("65c28fcf87156efe024c4558"), "Name" : { "First" : "Alan", "Last" : "Turing" }, "Birth" : ISODate("1912-05-23T06:00:00Z"), "Death" : ISODate("1954-05-07T05:00:00Z"), "Contribs" : ["Turing machine", "Turing test", "Turingery"], "Views" : 1250000 }
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data with C#, see the C# documentation.
The following sample application:
Establishes a connection to your Atlas cluster.
Inserts documents into a collection called
people
in thegettingStarted
database.Searches the
people
collection for documents that have aname.last
value ofTuring
and returns the document.
In your Go project with the driver and dependencies
installed, create a file called insert-data.go
and copy
the following code into the file:
Note
Replace the placeholder with your Atlas connection string.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 // Define structure of documents in the people collection 14 type Person struct { 15 Name Name 16 Birth time.Time 17 Death time.Time 18 Contribs []string 19 Views int 20 } 21 22 type Name struct { 23 First string 24 Last string 25 } 26 27 func main() { 28 29 // Replace the following with your Atlas connection string 30 uri := "<connection-string>" 31 32 // Connect to your Atlas cluster 33 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)) 34 if err != nil { 35 panic(err) 36 } 37 defer client.Disconnect(context.TODO()) 38 39 // Reference the database and collection to use 40 collection := client.Database("gettingStarted").Collection("people") 41 42 // Create new documents 43 newPeople := []interface{}{ 44 Person{ 45 Name: Name{First: "Alan", Last: "Turing"}, 46 Birth: time.Date(1912, 5, 23, 0, 0, 0, 0, time.UTC), // May 23, 1912 47 Death: time.Date(1954, 5, 7, 0, 0, 0, 0, time.UTC), // May 7, 1954 48 Contribs: []string{"Turing machine", "Turing test", "Turingery"}, 49 Views: 1250000, 50 }, 51 Person{ 52 Name: Name{First: "Grace", Last: "Hopper"}, 53 Birth: time.Date(1906, 12, 9, 0, 0, 0, 0, time.UTC), // Dec 9, 1906 54 Death: time.Date(1992, 1, 1, 0, 0, 0, 0, time.UTC), // Jan 1, 1992 55 Contribs: []string{"Mark I", "UNIVAC", "COBOL"}, 56 Views: 3860000, 57 }, 58 } 59 60 // Insert the document into the specified collection 61 collection.InsertMany(context.TODO(), newPeople) 62 63 // Find the document 64 collection = client.Database("gettingStarted").Collection("people") 65 filter := bson.D{{"name.last", "Turing"}} 66 67 var result Person 68 err = collection.FindOne(context.TODO(), filter).Decode(&result) 69 if err != nil { 70 panic(err) 71 } 72 73 // Print results 74 fmt.Printf("Document Found:\n%+v\n", result) 75 }
To run the sample application, use the following command:
go run insert-data.go
Document Found: {Name:{First:Alan Last:Turing} Birth:1912-06-23 06:00:00 +0000 UTC Death:1954-06-07 05:00:00 +0000 UTC Contribs:[Turing machine Turing test Turingery] Views:1250000}
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data with Go, see the Go documentation.
The following sample application:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Inserts documents into a collection called
people
in thegettingStarted
database.Searches the
people
collection for documents that have aname.last
value ofTuring
and returns the document.
In your Java project with the driver and dependencies
installed, create a file called InsertData.java
and copy
the following code into the file:
Note
Replace the placeholder with your Atlas connection string.
1 import static com.mongodb.client.model.Filters.eq; 2 import com.mongodb.client.MongoClient; 3 import com.mongodb.client.MongoClients; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoDatabase; 6 import com.mongodb.client.result.InsertManyResult; 7 import com.mongodb.MongoException; 8 9 import java.util.Arrays; 10 import java.util.List; 11 import java.util.Date; 12 import java.time.Instant; 13 import org.bson.types.ObjectId; 14 import org.bson.Document; 15 16 public class InsertData { 17 public static void main(String[] args) { 18 // Replace the placeholder with your Atlas connection string 19 String uri = "<connection-string>"; 20 21 // Connect to your Atlas Cluster and insert a document 22 try (MongoClient mongoClient = MongoClients.create(uri)) { 23 // Reference the database and collection to use 24 MongoDatabase database = mongoClient.getDatabase("gettingStarted"); 25 MongoCollection<Document> collection = database.getCollection("people"); 26 27 // Create two documents 28 List<Document> peopleList = Arrays.asList( 29 new Document().append("name", new Document().append("first", "Alan").append("last", "Turing")) 30 .append("birth", Date.from(Instant.parse("1912-05-23T00:00:00.000+00:00"))) 31 .append("death", Date.from(Instant.parse("1954-05-07T00:00:00.000+00:00"))) 32 .append("contribs", Arrays.asList("Turing machine", "Turing test", "Turingery")) 33 .append("views", 1250000), 34 new Document().append("name", new Document().append("first", "Grace").append("last", "Hopper")) 35 .append("birth", Date.from(Instant.parse("1906-12-09T00:00:00.000+00:00"))) 36 .append("death", Date.from(Instant.parse("1992-01-01T00:00:00.000+00:00"))) 37 .append("contribs", Arrays.asList("Mark I", "UNIVAC", "COBOL")) 38 .append("views", 3860000) 39 ); 40 41 try { 42 // Insert the documents into the specified collection 43 InsertManyResult result = collection.insertMany(peopleList); 44 } catch (MongoException me) { 45 System.err.println("Unable to insert due to an error: " + me); 46 } 47 // Find the document 48 Document document = collection.find(eq("name.last", "Turing")) 49 .first(); 50 51 // Print results 52 if (document == null) { 53 System.out.println("No results found."); 54 } else { 55 System.out.println("Document found:"); 56 System.out.println(document.toJson()); 57 } 58 } 59 } 60 }
Then, compile and run the SortDateForSpeed.java file:
javac InsertData.java java InsertData
Document found: {"_id": {"$oid": "64d52c3c3db2144fc00791b9"}, "name": {"first": "Alan", "last": "Turing"}, "birth": {"$date": {"$numberLong": "-1815328800000"}}, "death": {"$date": {"$numberLong": "-491338800000"}}, "contribs": ["Turing machine", "Turing test", "Turingery"], "views": 1250000}
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data with Java, see the Java documentation.
The following sample application:
Establishes a connection to your Atlas cluster.
Inserts documents into a collection called
people
in thegettingStarted
database.Searches the
people
collection for documents that have aname.last
value ofTuring
and returns the document.
Create a file called insert-data.js
and copy the following
code into the file:
Note
Replace the placeholder with your Atlas connection string.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the following with your Atlas connection string 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 // Connect to the Atlas cluster 12 await client.connect(); 13 14 // Get the database and collection on which to run the operation 15 const db = client.db("gettingStarted"); 16 const col = db.collection("people"); 17 18 // Create new documents 19 const peopleDocuments = [ 20 { 21 "name": { "first": "Alan", "last": "Turing" }, 22 "birth": new Date(1912, 5, 23), // May 23, 1912 23 "death": new Date(1954, 5, 7), // May 7, 1954 24 "contribs": [ "Turing machine", "Turing test", "Turingery" ], 25 "views": 1250000 26 }, 27 { 28 "name": { "first": "Grace", "last": "Hopper" }, 29 "birth": new Date(1906, 12, 9), // Dec 9, 1906 30 "death": new Date(1992, 1, 1), // Jan 1, 1992 31 "contribs": [ "Mark I", "UNIVAC", "COBOL" ], 32 "views": 3860000 33 } 34 ] 35 36 // Insert the documents into the specified collection 37 const p = await col.insertMany(peopleDocuments); 38 39 // Find the document 40 const filter = { "name.last": "Turing" }; 41 const document = await col.findOne(filter); 42 43 // Print results 44 console.log("Document found:\n" + JSON.stringify(document)); 45 46 } catch (err) { 47 console.log(err.stack); 48 } 49 50 finally { 51 await client.close(); 52 } 53 } 54 55 run().catch(console.dir);
To run the sample application, use the following command:
node insert-data.js
Document found: {"_id":"65c296ae128a3f34abda47e0","name":{"first":"Alan","last":"Turing"},"birth":"1912-06-23T06:00:00.000Z","death":"1954-06-07T05:00:00.000Z","contribs":["Turing machine","Turing test","Turingery"],"views":1250000}
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data with Node.js, see the Node.js documentation.
The following sample application:
Establishes a connection to your Atlas cluster.
Inserts documents into a collection called
people
in thegettingStarted
database.Searches the
people
collection for documents that have aname.last
value ofTuring
and returns the document.
In your Python project with the driver and dependencies
installed, create a file called insert-data.py
and copy
the following code into the file:
Note
Replace the placeholder with your Atlas connection string.
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient('<connection-string>') 6 7 # get the database and collection on which to run the operation 8 collection = client['gettingStarted']['people'] 9 10 # create new documents 11 peopleDocuments = [ 12 { 13 "name": { "first": "Alan", "last": "Turing" }, 14 "birth": datetime.datetime(1912, 6, 23), 15 "death": datetime.datetime(1954, 6, 7), 16 "contribs": [ "Turing machine", "Turing test", "Turingery" ], 17 "views": 1250000 18 }, 19 { 20 "name": { "first": "Grace", "last": "Hopper" }, 21 "birth": datetime.datetime(1906, 12, 9), 22 "death": datetime.datetime(1992, 1, 1), 23 "contribs": [ "Mark I", "UNIVAC", "COBOL" ], 24 "views": 3860000 25 } 26 ] 27 28 # insert documents 29 collection.insert_many(peopleDocuments) 30 31 # find documents 32 result = collection.find_one({ "name.last": "Turing" }) 33 34 # print results 35 print("Document found:\n", result)
To run the sample application, use the following command:
1 python insert-data.py
Document found: { '_id': ObjectId('65c2a8188388383b00a85b1f'), 'name': { 'first': 'Alan', 'last': 'Turing' }, 'birth': datetime.datetime(1912, 6, 23, 0, 0), 'death': datetime.datetime(1954, 6, 7, 0, 0), 'contribs': [ 'Turing machine', 'Turing test', 'Turingery' ], 'views': 1250000 }
Note
You might see a different value for ObjectId, because it is a system-generated value.
Tip
To learn more about querying data with PyMongo, see the PyMongo documentation.
Next Steps
If you continue to grow your cluster, consider scaling your cluster to support more users and operations.
You can load a sample dataset to quickly start experimenting with data in MongoDB and using tools such as the Atlas UI and MongoDB Charts. To learn more, see Load Data into Atlas.
You can also generate synthetic data. To learn more, see Generate Synthetic Data.