Docs 菜单
Docs 主页
/
入门指南

将数据插入 MongoDB

在本指南中,您将向 MongoDB 插入数据。

所需时间:15 分钟

  • stringMongoDB部署的 连接 。

  • 加载到集群中的示例数据集。

  • 已安装的 MongoDB 驱动程序

1
1

以下类列出了文档将具有的所有字段名称和类型。

CrudInsert.cs
1// class that maps to the fields of a document in the sample_guides.comets collection
2class Comet {
3 public ObjectId Id { get; set; }
4 public string Name { get; set; }
5 public string OfficialName { get; set; }
6 public double OrbitalPeriod { get; set; }
7 public double Radius { get; set; }
8 public double Mass { get; set; }
9}
2

在C#中,将字段映射到类属性,按照惯例,类属性为大写。 但是,您应该使用混合使用大小写字段插入数据。 要使驾驶员自动将字段从大写转换为驼峰式大小写,请创建 ConventionPack并注册CamelCase的命名约定。

CrudInsert.cs
1// instruct the driver to camelCase the fields in MongoDB
2var pack = new ConventionPack { new CamelCaseElementNameConvention() };
3ConventionRegistry.Register("elementNameConvention", pack, x => true);
3

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来插入数据。

在第 6 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

CrudInsert.cs
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Conventions;
3using MongoDB.Driver;
4
5// Replace the uri string with your MongoDB deployment's connection string.
6var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
7
8// instruct the driver to camelCase the fields in MongoDB
9var pack = new ConventionPack { new CamelCaseElementNameConvention() };
10ConventionRegistry.Register("elementNameConvention", pack, x => true);
11
12var client = new MongoClient(uri);
13
14// database and colletion code goes here
15// insert code goes here
16// display the results of your operation
17
18// class that maps to the fields of a document in the sample_guides.comets collection
19class Comet {
20 public ObjectId Id { get; set; }
21 public string Name { get; set; }
22 public string OfficialName { get; set; }
23 public double OrbitalPeriod { get; set; }
24 public double Radius { get; set; }
25 public double Mass { get; set; }
26}

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来插入数据。

在第 13 行,将 URI string替换为您自己的Atlas连接string 。

crud-insert.go
1import (
2 "context"
3 "fmt"
4 "log"
5 "os"
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 defer func() {
20 if err = client.Disconnect(context.TODO()); err != nil {
21 panic(err)
22 }
23 }()
24
25 // database and colletion code goes here
26 // insert code goes here
27 // display the results of your operation
28}

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来插入数据。

在第 15 行,将 URI string替换为您自己的Atlas连接string 。

CrudInsert.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.result.InsertManyResult;
6
7import org.bson.Document;
8import org.bson.types.ObjectId;
9
10import java.util.List;
11import java.util.ArrayList;
12
13public class CrudInsert {
14 public static void main(String[] args) {
15 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
16
17 try (MongoClient mongoClient = MongoClients.create(uri)) {
18 // database and collection code goes here
19 // insert code goes here
20 // display the results of your operation
21 }
22 }
23}

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来插入数据。

在第 4 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

crud-insert.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 // insert code goes here
11 // display the results of your operation
12 } finally {
13 // Ensures that the client will close when you finish/error
14 await client.close();
15 }
16}
17run().catch(console.dir);

提示

下面概述了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来插入数据。

在第 4 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

crud_insert.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# insert code goes here
10# display the results of your operation
11
12# Close the connection to MongoDB when you're done.
13client.close()

提示

mongodb+srv

确保您已安装带 srv 选项的 PyMongo。

python3 -m pip install "pymongo[srv]"
2

切换到要使用的数据库和集合。在本例中,您将使用 sample_guides 数据库和 comets 集合。

CrudInsert.cs
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<Comet>("comets");
crud-insert.go
1// database and colletion code goes here
2db := client.Database("sample_guides")
3coll := db.Collection("comets")
CrudInsert.java
1// database and collection code goes here
2MongoDatabase db = mongoClient.getDatabase("sample_guides");
3MongoCollection<Document> coll = db.getCollection("comets");
crud-insert.js
// database and collection code goes here
const db = client.db("sample_guides");
const coll = db.collection("comets");
crud_insert.py
# database and collection code goes here
db = client.sample_guides
coll = db.comets
3

comets 集合创建并插入三个新文档。每个文档都包含有关该彗星的以下信息:

  • 名称

  • 官方名称

  • 以年为单位的轨道周期

  • 半径(以英里为单位)

  • 质量(千克)

CrudInsert.cs
// insert code goes here
var comets = new [] {
new Comet {
Name = "Halley's Comet",
OfficialName = "1P/Halley",
OrbitalPeriod = 75,
Radius = 3.4175,
Mass = 2.2e14
},
new Comet {
Name = "Wild2",
OfficialName = "81P/Wild",
OrbitalPeriod = 6.41,
Radius = 1.5534,
Mass = 2.3e13
},
new Comet {
Name = "Comet Hyakutake",
OfficialName = "C/1996 B2",
OrbitalPeriod = 17000,
Radius = 0.77671,
Mass = 8.8e12
}
};
coll.InsertMany(comets);
crud-insert.go
1// insert code goes here
2docs := []interface{}{
3 bson.D{{"name", "Halley's Comet"}, {"officialName", "1P/Halley"}, {"orbitalPeriod", 75}, {"radius", 3.4175}, {"mass", 2.2e14}},
4 bson.D{{"name", "Wild2"}, {"officialName", "81P/Wild"}, {"orbitalPeriod", 6.41}, {"radius", 1.5534}, {"mass", 2.3e13}},
5 bson.D{{"name", "Comet Hyakutake"}, {"officialName", "C/1996 B2"}, {"orbitalPeriod", 17000}, {"radius", 0.77671}, {"mass", 8.8e12}},
6}
7
8result, err := coll.InsertMany(context.TODO(), docs)
9if err != nil {
10 panic(err)
11}
CrudInsert.java
1// insert code goes here
2List<Document> documents = new ArrayList<>();
3
4Document doc1 = new Document("name", "Halley's Comet").append("officialName", "1P/Halley").append("orbitalPeriod", 75).append("radius", 3.4175).append("mass", 2.2e14);
5Document doc2 = new Document("name", "Wild2").append("officialName", "81P/Wild").append("orbitalPeriod", 6.41).append("radius", 1.5534).append("mass", 2.3e13);
6Document doc3 = new Document("name", "Comet Hyakutake").append("officialName", "C/1996 B2").append("orbitalPeriod", 17000).append("radius", 0.77671).append("mass", 8.8e12);
7
8documents.add(doc1);
9documents.add(doc2);
10documents.add(doc3);
11
12InsertManyResult result = coll.insertMany(documents);
crud-insert.js
// insert code goes here
const docs = [
{name: "Halley's Comet", officialName: "1P/Halley", orbitalPeriod: 75, radius: 3.4175, mass: 2.2e14},
{name: "Wild2", officialName: "81P/Wild", orbitalPeriod: 6.41, radius: 1.5534, mass: 2.3e13},
{name: "Comet Hyakutake", officialName: "C/1996 B2", orbitalPeriod: 17000, radius: 0.77671, mass: 8.8e12}
];
const result = await coll.insertMany(docs);
crud_insert.py
# insert code goes here
docs = [
{"name": "Halley's Comet", "officialName": "1P/Halley", "orbitalPeriod": 75, "radius": 3.4175, "mass": 2.2e14},
{"name": "Wild2", "officialName": "81P/Wild", "orbitalPeriod": 6.41, "radius": 1.5534, "mass": 2.3e13},
{"name": "Comet Hyakutake", "officialName": "C/1996 B2", "orbitalPeriod": 17000, "radius": 0.77671, "mass": 8.8e12},
]
result = coll.insert_many(docs)

提示

如果省略 _id 字段,驱动程序会自动为 _id 字段生成唯一的 ObjectId 值。

4

MongoDB 中的许多写入操作都会返回一个包含操作信息的结果对象。

对于插入操作,C# 驱动程序会自动创建所插入文档的 _id。在这里,您将从原始数组访问此属性并将其输出。

CrudInsert.cs
// display the results of your operation
foreach (var comet in comets) {
Console.WriteLine(comet.Id);
}

对于插入操作,结果对象将包含驱动程序成功插入的文档的 _id。在这里,您将访问此属性并将其打印出来。

crud-insert.go
1// display the results of your operation
2for _, id := range result.InsertedIDs {
3 fmt.Printf("\t%s\n", id)
4}

对于插入操作,结果对象将包含驱动程序成功插入的文档的 _id。在这里,您将访问此属性并将其打印出来。

CrudInsert.java
1// display the results of your operation
2result.getInsertedIds().values().forEach(doc -> System.out.println(doc.asObjectId().getValue()));

对于插入操作,结果对象将包含驱动程序成功插入的文档的 _id。在这里,您将访问此属性并将其打印出来。

crud-insert.js
// display the results of your operation
console.log(result.insertedIds);

对于插入操作,结果对象将包含驱动程序成功插入的文档的 _id。在这里,您将访问此属性并将其打印出来。

crud_insert.py
# display the results of your operation
print(result.inserted_ids)
5

以下是完整的代码,然后是样本输出。

注意

您的 ObjectId 值将与显示的值不同。

CrudInsert.cs
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Conventions;
3using MongoDB.Driver;
4
5// Replace the uri string with your MongoDB deployment's connection string.
6var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
7
8// instruct the driver to camelCase the fields in MongoDB
9var pack = new ConventionPack { new CamelCaseElementNameConvention() };
10ConventionRegistry.Register("elementNameConvention", pack, x => true);
11
12var client = new MongoClient(uri);
13
14// database and colletion code goes here
15var db = client.GetDatabase("sample_guides");
16var coll = db.GetCollection<Comet>("comets");
17
18// insert code goes here
19var comets = new [] {
20 new Comet {
21 Name = "Halley's Comet",
22 OfficialName = "1P/Halley",
23 OrbitalPeriod = 75,
24 Radius = 3.4175,
25 Mass = 2.2e14
26 },
27 new Comet {
28 Name = "Wild2",
29 OfficialName = "81P/Wild",
30 OrbitalPeriod = 6.41,
31 Radius = 1.5534,
32 Mass = 2.3e13
33 },
34 new Comet {
35 Name = "Comet Hyakutake",
36 OfficialName = "C/1996 B2",
37 OrbitalPeriod = 17000,
38 Radius = 0.77671,
39 Mass = 8.8e12
40 }
41};
42
43coll.InsertMany(comets);
44
45// display the results of your operation
46foreach (var comet in comets) {
47 Console.WriteLine(comet.Id);
48}
49
50// class that maps to the fields of a document in the sample_guides.comets collection
51class Comet {
52 public ObjectId Id { get; set; }
53 public string Name { get; set; }
54 public string OfficialName { get; set; }
55 public double OrbitalPeriod { get; set; }
56 public double Radius { get; set; }
57 public double Mass { get; set; }
58}
625604fbd301606fd9998b14
625604fbd301606fd9998b15
625604fbd301606fd9998b16
crud-insert.go
1import (
2 "context"
3 "fmt"
4 "log"
5 "os"
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 defer func() {
20 if err = client.Disconnect(context.TODO()); err != nil {
21 panic(err)
22 }
23 }()
24
25 // database and colletion code goes here
26 db := client.Database("sample_guides")
27 coll := db.Collection("comets")
28
29 // insert code goes here
30 docs := []interface{}{
31 bson.D{{"name", "Halley's Comet"}, {"officialName", "1P/Halley"}, {"orbitalPeriod", 75}, {"radius", 3.4175}, {"mass", 2.2e14}},
32 bson.D{{"name", "Wild2"}, {"officialName", "81P/Wild"}, {"orbitalPeriod", 6.41}, {"radius", 1.5534}, {"mass", 2.3e13}},
33 bson.D{{"name", "Comet Hyakutake"}, {"officialName", "C/1996 B2"}, {"orbitalPeriod", 17000}, {"radius", 0.77671}, {"mass", 8.8e12}},
34 }
35
36 result, err := coll.InsertMany(context.TODO(), docs)
37 if err != nil {
38 panic(err)
39 }
40
41 // display the results of your operation
42 for _, id := range result.InsertedIDs {
43 fmt.Printf("\t%s\n", id)
44 }
45}
ObjectID("624cf31b350635c487d55215")
ObjectID("624cf31b350635c487d55216")
ObjectID("624cf31b350635c487d55217")
CrudInsert.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.result.InsertManyResult;
6
7import org.bson.Document;
8
9import java.util.List;
10import java.util.ArrayList;
11
12public class CrudInsert {
13 public static void main(String[] args) {
14 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
15
16 try (MongoClient mongoClient = MongoClients.create(uri)) {
17 // database and collection code goes here
18 MongoDatabase db = mongoClient.getDatabase("sample_guides");
19 MongoCollection<Document> coll = db.getCollection("comets");
20
21 // insert code goes here
22 List<Document> documents = new ArrayList<>();
23
24 Document doc1 = new Document("name", "Halley's Comet").append("officialName", "1P/Halley").append("orbitalPeriod", 75).append("radius", 3.4175).append("mass", 2.2e14);
25 Document doc2 = new Document("name", "Wild2").append("officialName", "81P/Wild").append("orbitalPeriod", 6.41).append("radius", 1.5534).append("mass", 2.3e13);
26 Document doc3 = new Document("name", "Comet Hyakutake").append("officialName", "C/1996 B2").append("orbitalPeriod", 17000).append("radius", 0.77671).append("mass", 8.8e12);
27
28 documents.add(doc1);
29 documents.add(doc2);
30 documents.add(doc3);
31
32 InsertManyResult result = coll.insertMany(documents);
33
34 // display the results of your operation
35 result.getInsertedIds().values().forEach(doc -> System.out.println(doc.asObjectId().getValue()));
36 }
37 }
38}
625716fc5749232edfb4b2d7
625716fc5749232edfb4b2d8
625716fc5749232edfb4b2d9
crud-insert.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";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11 // database and collection code goes here
12 const db = client.db("sample_guides");
13 const coll = db.collection("comets");
14
15 // insert code goes here
16 const docs = [
17 {name: "Halley's Comet", officialName: "1P/Halley", orbitalPeriod: 75, radius: 3.4175, mass: 2.2e14},
18 {name: "Wild2", officialName: "81P/Wild", orbitalPeriod: 6.41, radius: 1.5534, mass: 2.3e13},
19 {name: "Comet Hyakutake", officialName: "C/1996 B2", orbitalPeriod: 17000, radius: 0.77671, mass: 8.8e12}
20 ];
21
22 const result = await coll.insertMany(docs);
23
24 // display the results of your operation
25 console.log(result.insertedIds);
26
27 } finally {
28 // Ensures that the client will close when you finish/error
29 await client.close();
30 }
31}
32run().catch(console.dir);
{
'0': 624d06994e68f44afe8c0da6,
'1': 624d06994e68f44afe8c0da7,
'2': 624d06994e68f44afe8c0da8
}
crud_insert.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.comets
11
12coll.drop()
13
14# insert code goes here
15docs = [
16 {"name": "Halley's Comet", "officialName": "1P/Halley", "orbitalPeriod": 75, "radius": 3.4175, "mass": 2.2e14},
17 {"name": "Wild2", "officialName": "81P/Wild", "orbitalPeriod": 6.41, "radius": 1.5534, "mass": 2.3e13},
18 {"name": "Comet Hyakutake", "officialName": "C/1996 B2", "orbitalPeriod": 17000, "radius": 0.77671, "mass": 8.8e12},
19 ]
20
21result = coll.insert_many(docs)
22
23# display the results of your operation
24print(result.inserted_ids)
25
26# Close the connection to MongoDB when you're done.
27client.close()
[ObjectId('624d078756f4582197aad408'), ObjectId('624d078756f4582197aad409'), ObjectId('624d078756f4582197aad40a')]

如已完成本指南,那么您已将数据插入到 MongoDB 中。

在下一篇指南中,您将了解如何更新文档中的字段。

如需深入了解此处介绍的概念,请参阅以下资源:

  • 插入文档

  • 插入方法

接下来的步骤
在 MongoDB 中更新数据
10 分钟

指定待更新的文档以及如何在 MongoDB 中更新。

入门指南
第2章
CRUD
  • 添加 MongoDB 驱动程序
  • 从 MongoDB 中读取数据
  • 通过查询从 MongoDB 中读取数据
  • 使用操作符和复合查询读取数据
  • 将数据插入 MongoDB
  • 在 MongoDB 中更新数据
  • 从 MongoDB 中删除数据