插入和查看文档
预计完成时间:5 分钟
连接到 Atlas 集群后,就可以与之交互。在本教程中,您将通过使用 mongosh
、Atlas 用户界面、MongoDB Compass 或支持的 MongoDB 驱动程序将数据插入集群并读取新数据。
➤ 使用选择您的语言下拉菜单设置本教程的方法。
必需的访问权限
要与集群交互,您必须是数据库用户。
先决条件
在开始之前,您必须配置首选连接方法。要了解更多信息,请参阅连接到您的集群。
插入并查看数据
Atlas 提供 GUI,用于与集群中的数据进行交互。
AtlasGoClusters在Atlas中,Go项目的 页面。
如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果尚未出现,请单击侧边栏中的 Clusters(集群)。
会显示集群页面。
转到 Collections(快速入门)页面。
单击集群的对应 Browse Collections 按钮。
显示数据浏览器。
将文档插入collection。
如果未选中
people
,则将其选中。单击 Insert Document(连接)。
单击 JSON 视图 ({}) 以替换默认文档。
粘贴以下代码:
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } 单击 Insert 添加文档。
单击 Insert Document(连接)。
单击 JSON 视图 ({}) 以替换默认文档。
粘贴以下代码:
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } 单击 Insert 添加文档。
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解更多信息,请参阅创建、查看、更新和删除文档。
将文档插入到数据库中。
在 mongosh
中,运行以下命令以将文档插入到新数据库中:
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') } }
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
此命令将在 gettingStarted
数据库中创建一个名为 people
的新集合,并将一个文档插入该集合。
查看文档。
要查看您刚插入到集群的文档之一,请运行以下命令以在 people
集合中搜索 name.last
值为 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") }
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解有关在 MongoDB 中查询数据的详情,请参阅查询文档。
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
将文档插入collection。
在左侧导航栏中,单击
gettingStarted
数据库。选择
people
集合。在集合的 Documents 选项卡中,单击 Add Data。
单击 Insert Document 并粘贴以下代码:
{ "name": { "first": "Alan", "last": "Turing" }, "birth": { "$date": "1912-06-23" }, "death": { "$date": "1954-06-07" }, "contribs": [ "Turing machine", "Turing test", "Turingery" ], "views": 1250000 } 单击 Insert 添加文档。
在集合的 Documents 选项卡中,单击 Add Data。
单击 Insert Document 并粘贴以下代码:
{ "name": { "first": "Grace", "last": "Hopper" }, "birth": { "$date": "1906-12-09" }, "death": { "$date": "1992-01-01" }, "contribs": [ "Mark I", "UNIVAC", "COBOL" ], "views": 3860000 } 单击 Insert 添加文档。
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解更多信息,请参阅 Compass 文档。
以下样本应用程序:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
将文档插入到
gettingStarted
数据库中名为people
的集合中。搜索
people
集群中name.last
值为Turing
的文档,并返回该文档。
在安装了驱动程序和依赖项的 .NET/C# 项目中,将以下代码复制到 Program.cs
文件中:
注意
将占位符替换为您的 Atlas 连接字符串。
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 }
要运行样本应用程序,请使用以下命令:
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 }
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解有关使用 C# 查询数据的更多信息,请参阅 C# 文档。
以下样本应用程序:
建立与您的 Atlas 集群的连接。
将文档插入到
gettingStarted
数据库中名为people
的集合中。搜索
people
集群中name.last
值为Turing
的文档,并返回该文档。
在安装了驱动程序和依赖项的 Go 项目中,创建一个名为 insert-data.go
的文件并将以下代码复制到该文件中:
注意
将占位符替换为您的 Atlas 连接字符串。
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 }
要运行样本应用程序,请使用以下命令:
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}
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解有关使用 Go 查询数据的更多信息,请参阅 Go 文档。
以下样本应用程序:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
将文档插入到
gettingStarted
数据库中名为people
的集合中。搜索
people
集群中name.last
值为Turing
的文档,并返回该文档。
在安装了驱动程序和依赖项的 Java 项目中,创建一个名为InsertData.java
的文件并将以下代码复制到该文件中:
注意
将占位符替换为您的 Atlas 连接字符串。
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 }
然后,编译并运行 SortDateForSpeed.java 文件:
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}
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解有关使用 Java 查询数据的更多信息,请参阅 Java 文档。
以下样本应用程序:
建立与您的 Atlas 集群的连接。
将文档插入到
gettingStarted
数据库中名为people
的集合中。搜索
people
集群中name.last
值为Turing
的文档,并返回该文档。
创建一个名为 insert-data.js
的文件并将以下代码复制到该文件中:
注意
将占位符替换为您的 Atlas 连接字符串。
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);
要运行样本应用程序,请使用以下命令:
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}
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
要了解有关使用 Node.js 查询数据的更多信息,请参阅 Node.js 文档。
以下样本应用程序:
建立与您的 Atlas 集群的连接。
将文档插入到
gettingStarted
数据库中名为people
的集合中。搜索
people
集群中name.last
值为Turing
的文档,并返回该文档。
在安装了驱动程序和依赖项的 Python 项目中,创建一个名为 insert-data.py
的文件并将以下代码复制到该文件中:
注意
将占位符替换为您的 Atlas 连接字符串。
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)
要运行样本应用程序,请使用以下命令:
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 }
注意
你可能会看到不同的 ObjectId 值,因为这是系统生成的值。
提示
如需了解有关使用 PyMongo 查询数据的更多信息,请参阅 PyMongo 文档。
后续步骤
如果您继续扩大集群,请考虑扩展集群,支持更多用户和操作。
您可以加载示例数据集,以便快速开始尝试使用 MongoDB 中的数据,并使用 Atlas 用户界面和 MongoDB Charts 等工具。要了解更多信息,请参阅将数据加载到 Atlas。
您还可以生成合成数据。要了解详情,请参阅生成合成数据。