Quick Start: C# and MongoDB快速起步:C#和MongoDB协同

原文地址:https://www.mongodb.com/blog/post/quick-start-c-sharp-and-mongodb-starting-and-setup

Starting and Setup启动和设置

In the first of the C# Quick Start series, I'll show how to set up connections between C# and MongoDB.在C#快速入门系列的第一部分中,我将展示如何在C和MongoDB之间建立连接。

In future parts we'll move on and work through:在以后的部分中,我们将继续并完成以下工作:

As you already know, C# is a general-purpose language and MongoDB is a general-purpose data platform. 如您所知,C#是通用语言,MongoDB是通用数据平台。Together, C# and MongoDB are a powerful combination.C#和MongoDB是一个强大的组合。

To follow along, I'll be using Visual Studio 2019 on Windows 10 and we will be connecting to a MongoDB Atlas cluster.接下来,我将在Windows 10上使用Visual Studio 2019,我们将连接到一个MongoDB Atlas群集。

Get started with an M0 cluster on MongoDB Atlas today. 现在就从MongoDB Atlas上的M0集群开始吧。It's free forever and you'll be able to work alongside this blog series.它永远是免费的,你将能够与这个博客系列一起工作。

If you're using a different OS, IDE, or text editor, the walkthrough might be slightly different, but the code itself should be fairly similar. 如果您使用的是不同的操作系统、IDE或文本编辑器,演练可能会略有不同,但代码本身应该非常相似。Let's jump in and take a look at how nicely C# and MongoDB work together.让我们来看看C#和MongoDB 是如何很好地协同工作的。

Getting Setup获取设置

For this demonstration, I’ve chosen to create a Console App (.NET Core), and I’ve named it MongoDBConnectionDemo.对于这个演示,我选择创建一个控制台应用程序(.NET Core),并将其命名为MongoDBConnectionDemo

Next, we need to install the MongoDB Driver for C#/.NET for a Solution. 下一步,我们需要为C#/.NET安装MongoDB驱动程序以获得解决方案。We can do that quite easily with NuGet. 我们可以很容易地用NuGet做到。Inside Visual Studio for Windows, by going to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution..._在Visual Studio for Windows内部,前往“工具”→“NuGet包管理器”→“为解决方案管理NuGet包...”

We can browse for MongoDB.Driver. 我们可以浏览MongoDB.DriverThen click on our Project and select the driver version we want. 然后点击我们的项目并选择我们想要的驱动程序版本。In this case, the latest stable version is 2.9.1. 在本例中,最新的稳定版本是2.9.1。Then click on Install. 然后单击“安装”。Accept any license agreements that pop up and head back to Program.cs to get started.接受任何弹出的许可协议,然后回到Program.cs开始。。

C# and MongoDB Driver Installation

Putting the Driver to Work让驱动程序起作用

To use the MongoDB.Driver we need to add a directive.使用MongoDB.Driver我们需要增加一个指令。

using MongoDB.Driver;

Inside the Main() method we’ll establish a connection to MongoDB Atlas with a connection string and to test the connection we’ll print out a list of the databases on the server. Main()方法中,我们将使用一个连接字符串建立到MongoDB Atlas的连接,为了测试连接,我们将打印出服务器上的数据库列表。The Atlas cluster to which we’ll be connecting has the MongoDB Atlas Sample Dataset installed, so we’ll be able to see a nice database list.我们将要连接的Atlas集群已经安装了MongoDB Atlas示例数据集,因此我们可以看到一个很好的数据库列表。

The first step is to pass in the MongoDB Atlas connection string into a MongoClient object, then we can get the list of databases and print them out.第一步是将MongoDB Atlas连接字符串传入MongoClient对象,然后我们可以获得数据库列表并将其打印出来。

MongoClient dbClient = new MongoClient(<<YOUR ATLAS CONNECTION STRING>>);
var dbList = dbClient.ListDatabases().ToList();
Console.WriteLine("The list of databases on this server is: ");
foreach (var db in dbList)
{
    Console.WriteLine(db);
}

When we run the program, we get the following out showing the list of databases:运行该程序时,会显示以下数据库列表:

The list of databases on this server is: 
{ "name" : "sample_airbnb", "sizeOnDisk" : 57466880.0, "empty" : false }
{ "name" : "sample_geospatial", "sizeOnDisk" : 1384448.0, "empty" : false }
{ "name" : "sample_mflix", "sizeOnDisk" : 45084672.0, "empty" : false }
{ "name" : "sample_supplies", "sizeOnDisk" : 1347584.0, "empty" : false }
{ "name" : "sample_training", "sizeOnDisk" : 73191424.0, "empty" : false }
{ "name" : "sample_weatherdata", "sizeOnDisk" : 4427776.0, "empty" : false }
{ "name" : "admin", "sizeOnDisk" : 245760.0, "empty" : false }
{ "name" : "local", "sizeOnDisk" : 1919799296.0, "empty" : false }

The whole program comes in at just over 20 lines of code:整个程序只有20多行代码:

using System;
using MongoDB.Driver;
namespace test
{
  class Program
  {
  static void Main(string[] args)
    {
    MongoClient dbClient = new MongoClient(<<YOUR ATLAS CONNECTION STRING>>);
    var dbList = dbClient.ListDatabases().ToList();
    Console.WriteLine("The list of databases on this server is: ");
    foreach (var db in dbList)
      {
          Console.WriteLine(db);
      }
    }
  }
}

C# and MongoDBC#和MongoDB

By developing with C# and MongoDB together one opens up a world of possibilities. 通过与C#和MongoDB协同开发,我们可以打开一个充满可能性的世界。Console, window, and web applications are all possible. 控制台、窗口和web应用程序都是可能的。As are cross-platform mobile applications using the Xamarin framework. 使用Xamarin框架的跨平台移动应用程序也是如此。Join me in this Quick Start series and learn how to perform CRUD operations with C# and MongoDB.加入这个快速入门系列,学习如何使用C#和MongoDB执行CRUD操作。

Creating Documents创建文档

In a previous post, I showed how to get C# and MongoDB connected. 在之前的一篇文章中,我展示了如何连接C#和MongoDB 。It is pretty straightforward to use the MongoDB.Driver from NuGet to establish a connection to a MongoDB server. 使用MongoDB.Driver从NuGet建立到MongoDB服务器的连接有点直截了当。In the case of this blog series, I'm using C# to connect to a MongoDB Atlas cluster that has the free demo data installed. 在本系列博客中,我使用C#连接到安装了免费演示数据的MongoDB Atlas集群。With a connection established, let's see how to use C# to do Create operations in MongoDB.在建立连接之后,让我们看看如何使用C#在MongoDB中执行创建操作。

Series Tools & Versions系列工具和版本

The tools and versions I'm using for this series are:我在本系列中使用的工具和版本是:

Data数据

MongoDB stores data in JSON Documents. MongoDB将数据存储在JSON文档中。Actually, they are stored as Binary JSON (BSON) objects on disk, but that's a subject for another blog post. 实际上,它们是作为二进制JSON(BSON)对象存储在磁盘上的,但这是另一篇博客文章的主题。In our sample dataset, there is a sample_training with a grades collection. 在我们的示例数据集中,存在一个sample_training集合以及一个grades集合。Here's what a sample document in that collection looks like:该集合中的示例文档如下所示:

{
    "_id": { "$oid":"56d5f7eb604eb380b0d8d8ce" },
    "student_id":{ "$numberDouble": "0" },
    "scores":[
        {"type":"exam","score": {"$numberDouble": "78.40446309504266" }},
        {"type":"quiz","score": {"$numberDouble": "73.36224783231339" }},
        {"type":"homework","score": {"$numberDouble": "46.980982486720535" }},
        {"type":"homework","score": {"$numberDouble": "76.67556138656222" }}
    ],
    "class_id":{"$numberDouble": "339"}
}

Connecting to a Specific Collection连接到特定集合

There are 10,000 students in this collection, 0-9,999. 这个集合有10000名学生,编号为0-9999。Let's add one more by using C#. 我们来利用C#新增一个。To do this, we'll need to use another package from NuGet, MongoDB.Bson. 为了实现为,我们需要使用另一个来自NuGet的包,MongoDB.BsonI'll start a new Solution in Visual Studio and call it MongoDBCRUDExample. 我将在Visual Studio中开始一个新的解决方案,并称它为MongoDBCRUDExampleI'll install the MongoDB.Bson and MongoDB.Driver packages and use the connection string provided from MongoDB Atlas. 我将安装MongDB.Bson包和MongoDB.Driver包,并使用MongoDB Altlas提供的连接字符串。Next, I'll access our specific database and collection, sample_training and grades, respectively.接下来,我将访问特定的数据库和集合,分别是sample_traininggradees

using System;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDBCRUDExample {
  class Program {
  static void Main (string[] args) {
    MongoClient dbClient = new MongoClient ( << YOUR ATLAS CONNECTION STRING >>);
    var database = dbClient.GetDatabase ("sample_training");
    var collection = database.GetCollection<BsonDocument> ("grades");
    }
  }
}

Creating a BSON Document创建BSON文档

The collection variable is now our key reference point to our data. 现在collection变量是对数据的关键引用点。Since we are using a BsonDocument when assigning our collection variable, I've indicated that I'm not going to be using a pre-defined schema. 由于我们在给collection变量赋值时使用BsonDocument,我表示我不打算使用一个预定义的架构。This utilizes the power and flexibility of MongoDB's document model. 这利用了MongoDB文档模型的强大功能和灵活性。I could define a plain-old-C#-object (POCO) to more strictly define a schema. 我可以定义一个普通的C#对象(POCO)来更严格地定义模式。I'll take a look at that option in a future post. 我将在以后的文章中研究这个选项。For now, I'll create a new BsonDocument to insert into the database.现在,我将创建一个新的BsonDocument来插入到数据库。

var document = new BsonDocument { { "student_id", 10000 }, {
  "scores",
  new BsonArray {
    new BsonDocument { { "type", "exam" }, { "score", 88.12334193287023 } },
    new BsonDocument { { "type", "quiz" }, { "score", 74.92381029342834 } },
    new BsonDocument { { "type", "homework" }, { "score", 89.97929384290324 } },
    new BsonDocument { { "type", "homework" }, { "score", 82.12931030513218 } }
    }
  }, { "class_id", 480 }
};

Create Operation创建操作

Then to Create the document in the sample_training.grades collection, we can do an insert operation.然后在sample_training.grades集合中创建文档,我们可以执行插入操作。

  collection.InsertOne(document);

If you need to do that insert asynchronously, the MongoDB C# driver is fully async compatible. 如果需要异步插入,MongoDB C#驱动程序是完全异步兼容的。The same operation could be done with:同样的操作可以在以下情况下进行:

  await collection.InsertOneAsync (document);

If you have a need to insert multiple documents at the same time, MongoDB has you covered there as well with the InsertMany or InsertManyAsync methods.如果你需要同时插入多个文档,MongoDB已经利用InsertMany方法和InsertManyAsync方法实现了这个要求。

Wrapping Up总结

We've seen how to structure a BSON Document in C# and then Create it inside a MongoDB database. 我们已经看到了如何在C#中结构化一个BSON,然后在MongoDB里面创建它。The MongoDB C# Driver makes it easy to do with the InsertOne(), InsertOneAsync(), InsertMany(), or InsertManyAsync() methods. MongoDB C#驱动程序可以利用InsertOne()方法、InsertOneAsync()方法、InsertMany()方法或InsertManyAsync()方法轻松实现它。As I mentioned, using a BSONDocument is convenient when a schema isn't defined. 如前所述,当没有定义模式时,使用BSONDocument非常方便。More frequently, however, the schema is defined in our code, not in the database itself. 然而,更常见的情况是,模式是在我们的代码中定义的,而不是在数据库本身中定义的。I'll take a look at mapping BSON data to a C# Class in an upcoming post.在接下来的一篇文章中,我将研究如何将BSON数据映射到C#类。

Now that we have Created data, we'll want to Read it. 既然我们已经创建了数据,我们将要读取它。I'll show that step in the CRUD process in my next post.我将在下一篇文章中展示CRUD过程中的这一步。

Get started with an M0 cluster on MongoDB Atlas today. 现在就从MongoDB Atlas上的M0集群开始吧。It's free forever and you'll be able to work alongside this blog series.它永远是免费的,你将能够与这个博客系列一起工作。

Read Operations读取操作

Welcome to the latest installment of the Quick Start C# and MongoDB series where we take on the second letter of CRUD. 欢迎来到C#和MongoDB快速入门系列的最新一期,我们将介绍CRUD的第二个字母。R is for Read. R表示读取So far we've looked at how to connect to a MongoDB Atlas cluster using C#, and then how to Create data in a collection. 到目前为止,我们已经了解了如何使用C#连接到MongoDB Atlas集群,以及如何在集合中创建数据。Now, we move on to reading that data.现在,我们继续阅读这些数据。

Created Data创建的数据

Just to recap, in the previous post on Create, I inserted the following BSONDocument into the sample_training.grades collection from the MongoDB sample dataset.简单回顾一下,在上一篇关于创建的文章中,我在来自MongoDB示例数据集的sample_training.grades集合中插入了以下BSONDocument

var document = new BsonDocument
{
    { "student_id", 10000 },
    { "scores", new BsonArray
        {
        new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
        new BsonDocument{ {"type", "quiz"}, {"score", 74.92381029342834 } },
        new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
        new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
        }
    },
    { "class_id", 480}
};

Read Operations读取操作

To Read documents in MongoDB, we use the Find() method. 若要在MongoDB中读取文档,我们使用Find()方法。This method allows us to chain a variety of methods to it, some of which I'll explore in this post. 这个方法允许我们将各种方法链接到它上面,我将在本文中探讨其中一些方法。To get the first document in the collection, we can use the FirstOrDefault or FirstOrDefaultAsync method, and print the result to the console.若要读取集合中的新文档,我们可以使用FirstOrDefault方法或FirstOrDefaultAsync方法,并将结果打印到控制台。

var firstDocument = collection.Find(new BsonDocument()).FirstOrDefault();
Console.WriteLine(firstDocument.ToString());

returns...返回了…

{ "_id" : ObjectId("56d5f7eb604eb380b0d8d8ce"), 
  "student_id" : 0.0, 
  "scores" : [
    { "type" : "exam", "score" : 78.404463095042658 },
    { "type" : "quiz", "score" : 73.362247832313386 }, 
    { "type" : "homework", "score" : 46.980982486720535 }, 
    { "type" : "homework", "score" : 76.675561386562222 }
  ], 
  "class_id" : 339.0 
}

You may wonder why we aren't using Single as that returns one document too. 您可能想知道为什么我们不使用Single,即使它也返回一个文档。Well, that has to also ensure the returned document is the only document like that in the collection and that means scanning the whole collection.好吧,这还必须确保返回的文档是集合中唯一这样的文档,这意味着扫描整个集合。

Reading with a Filter用筛选器读取

Let's find the document we created and print it out to the console. 让我们来找到我们刚创建的文档并在控制台中打印它。The first step is to create a filter to query for our specific document.第一步是创建一个筛选器来查询我们的特定文档。

var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);

Here we're setting a filter to look for a document where the student_id is equal to 10000. 此处我们设置了一个筛选器来找到student_id等于10000的文档。We can pass the filter into the Find() method to get the first document that matches the query.我们可以把筛选器传入到Find()方法以取得匹配查询的第一个文档。

var studentDocument = collection.Find(filter).FirstOrDefault();
Console.WriteLine(studentDocument.ToString());

returns...返回了…

{ "_id" : ObjectId("5d88f88cec6103751b8a0d7f"), 
  "student_id" : 10000, 
  "scores" : [
    { "type" : "exam", "score" : 88.123341932870233 }, 
    { "type" : "quiz", "score" : 74.923810293428346 }, 
    { "type" : "homework", "score" : 89.979293842903246 }, 
    { "type" : "homework", "score" : 82.129310305132179 }
  ], 
  "class_id" : 480 
}

If a document isn't found that matches the query, the Find() method returns null. 如果没能找到一个匹配查询的文档,Find()方法将返回null。Finding the first document in a collection, or with a query is a frequent task. 查找集合中的第一个文档或利用查询查找文档是一项常见的任务。However, what about situations when all documents need to be returned, either in a collection or from a query?但是,如果需要返回所有文档,无论是在集合中还是从查询中返回,该怎么办?

Reading All Documents读取所有文档

For situations in which the expected result set is small, the ToList() or ToListAsync() methods can be used to retrieve all documents from a query or in a collection.对于预期结果集较小的情况,可以使用ToList()方法或ToListAsync()方法从查询或集合中检索所有文档。

var documents = collection.Find(new BsonDocument()).ToList();

We can iterate over that list and print the results like so:我们可以迭代该列表并按如下方式打印结果:

foreach(BsonDocument doc in documents)
{
    Console.WriteLine(doc.ToString());
}

Filters can be passed in here as well, for example, to get documents with exam scores equal or above 95. 筛选器也可以在这里传递,例如,获取考试分数等于或高于95的文档。The filter here looks slightly more complicated, but thanks to the MongoDB driver syntax, it is relatively easy to follow. 这里的筛选器看起来稍微复杂一点,但是多亏了MongoDB驱动程序语法,它相对容易理解。We're filtering on documents in which inside the scores array there is an exam subdocument with a score value greater than or equal to 95.我们过滤的文档中,scores数组内有一个exam子文档,带有大于或等于95的score值。

var highExamScoreFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>(
    "scores", new BsonDocument { { "type", "exam" },
    { "score", new BsonDocument { { "$gte", 95 } } }
});
var highExamScores = collection.Find(highExamScoreFilter).ToList();

Where there's more than a small list of results you need it retrieve, the Find method can be made to return a cursor with ToCursor which points to the records that need to be retrieved. 如果需要检索的结果不止一个小列表,那么可以使用Find方法返回一个游标,其ToCursor指向需要检索的记录。This cursor can be used in a foreach statement in a synchronous situations by using the ToEnumerable adapter method.通过使用ToEnumerable适配器方法,可以在同步情况下的foreach语句中使用此游标。

var cursor = collection.Find(highExamScoreFilter).ToCursor();
foreach (var document in cursor.ToEnumerable())
{
     Console.WriteLine(document);
}

This can be accomplished asynchronously with the ForEachAsync method:这可以通过ForEachAsync方法异步完成:

await collection.Find(highExamScoreFilter)
     .ForEachAsync(document => Console.WriteLine(document));

Sorting排序

With many documents coming back in the result set, it is often helpful to sort the results. 由于结果集中返回了许多文档,因此对结果进行排序通常很有帮助。We can use the Sort() method to accomplish this to see which student had the highest exam score. 我们可以使用Sort()方法来完成这个任务,看看哪个学生的考试成绩最高。Note that the sort method asks the database to do the sorting; it's not performed by the driver or application.请注意,sort方法要求数据库进行排序;它不是由驱动程序或应用程序执行的。

var sort = Builders<BsonDocument>.Sort.Descending("student_id");
var highestScores = collection.Find(highExamScoreFilter).Sort(sort);

And we can append the First() method to that to just get the top student.我们可以将First()方法追加到该方法后面,以获得最优秀的学生。

var highestScore = collection.Find(highExamScoreFilter).Sort(sort).First();
Console.WriteLine(highestScore);

Based on the Atlas Sample Data Set, the document with a student_id of 9997 should be returned with an exam score of 95.441609472871946.根据Atlas样本数据集student_id编号为9997的文件应返回考试成绩为95.441609472871946。

You can see the full code for both the Create and Read operations I've shown in the gist here.您可以看到我在这里的要点中《展示的创建读取操作的完整代码。

Wrap Up总结

The C# Driver for MongoDB provides many ways to Read data from the database and supports both synchronous and asynchronous methods for querying the data. MongoDB的C#驱动程序提供了多种从数据库读取数据的方法,并支持查询数据的同步和异步方法。By passing a filter into the Find() method, we are able to query for specific records. 通过向Find()方法传递筛选器,我们可以查询特定的记录。The syntax to build filters and query the database is straightforward and easy to read, making this step of CRUD operations in C# and MongoDB simple to use.构建过滤器和查询数据库的语法简单明了,易于阅读,使得这一步的CRUD操作在C#和MongoDB中易于使用。

Next up in this C# Quick Start CRUD operation series, I'll take a look at how to Update documents. 在这个快速入门CRUD操作系列的下一个部分,我将介绍如何更新文档。Once again, the C# Driver for MongoDB provides a nice interface for this step and both sync and async versions.同样,MongoDB的C#驱动程序为这个步骤以及同步和异步版本提供了一个很好的接口。

Get started with an M0 cluster on MongoDB Atlas today. 现在就从MongoDB Atlas上的M0集群开始吧。It's free forever and you'll be able to work alongside this blog series.它永远是免费的,你将能够与这个博客系列一起工作。

Update Operations更新操作

In the last edition of this C# Quick Start for MongoDB CRUD operations, we explored some of the different ways to Read data. 最新版的MongoDB CRUD操作快速入门中,我们探讨了一些读取数据的不同方法。We saw how to add filters to our query and how to sort the data. 我们了解了如何向查询添加过滤器以及如何对数据进行排序。This post is about the Update operation and how the C# driver's Update and MongoDB work together to accomplish this important task.这篇文章是关于更新操作的,以及C#驱动程序的更新和MongoDB 是如何协同工作来完成这项重要任务的。

Recall that we've been working with this BsonDocument version of a student record:回想一下,我们一直在处理学生记录的以下BsonDocument版本:

var document = new BsonDocument
{
  { "student_id", 10000 },
  { "scores", new BsonArray
    {
    new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
    new BsonDocument{ {"type", "quiz"}, {"score", 74.92381029342834 } },
    new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
    new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
    }
  },
  { "class_id", 480}
};

After getting part way through the grading term, our sample student's instructor notices that he's been attending the wrong class section. 在完成了部分的评分后,我们的样本学生的导师发现他上错了课。Due to this error the school administration has to change, or update, the class_id associated with his record. 由于这个错误,学校管理部门必须更改或更新与他记录相关的class_idHe'll be moving into section 483.他将搬进483区。

Updating Data更新数据

To update a document we need two bits to pass into an Update command. 要更新文档,我们需要两个位来传递到Update命令中。We need a filter to determine which documents will be updated. 我们需要一个筛选器器来确定哪些文档将被更新。Second, we need what we're wanting to update.其次,我们需要我们想要更新的东西。

Update Filter更新筛选器

For our example, we want to filter based on the document with student_id equaling 10000.对于我们的示例,我们希望根据student_id等于10000的文档进行过滤。

var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000)

Data to be Changed要更改的数据

Next, we want to make the change to the class_id. 接下来,我们想要修改到class_idWe can do that with Set() on the Update() method.我们可以在Update()方法上利用Set()来实现这。

var update = Builders<BsonDocument>.Update.Set("class_id", 483);

Then we use the UpdateOne() method to make the changes. 然后使用UpdateOne()方法来实现更改。Note here that MongoDB will update at most one document using the UpdateOne() method. 请注意使用UpdateOne()方法的话,MongoDB将最多更新一个文档。If no documents match the filter, no documents will be updated.如果没有文档匹配筛选器,则不会有文档被更新。

collection.UpdateOne(filter, update);

Array Changes数组更新

Not all changes are as simple as changing a single field. 并非所有更改都像更改单个字段那样简单。Let's use a different filter, one that selects a document with a particular score type for quizzes:让我们使用一个不同的筛选器,它可以为测验选择具有特定分数类型的文档:

var arrayFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000) 
     & Builders<BsonDocument>.Filter.Eq("scores.type", "quiz");

Now if we want to make the change to the quiz score we can do that with Set() too, but to identify which particular element should be changed is a little different. 现在,如果我们想对测验分数进行更改,我们也可以使用Set()来进行更改,但是要确定应该更改哪个特定的元素有点不同。We can use the positional $ operator to access the quiz score in the array. 我们可以使用定位$运算符来访问数组中的quizscoreThe $ operator on its own says "change the array element that we matched within the query" - the filter matches with scores.type equal to quiz and that element will get updated with the set.$运算符本身表示“更改我们在查询中匹配的数组元素”—只要筛选器匹配scores.type等于“quiz”,则该元素将随集合更新。

var arrayUpdate = Builders<BsonDocument>.Update.Set("scores.$.score", 84.92381029342834);

And again we use the UpdateOne() method to make the changes.我们再次使用UpdateOne()方法进行更改。

collection.UpdateOne(arrayFilter , arrayUpdate);

Additional Update Methods其他更新方法

If you've been reading along in this blog series I've mentioned that the C# driver supports both sync and async interactions with MongoDB. 如果您一直在阅读本系列博客,我已经提到过C#驱动程序支持与MongoDB的同步和异步交互。Performing data Updates is no different. 执行数据更新也没什么不同。There is also an UpdateOneAsync() method available. 还有一个updateOneSync()方法可用。Additionally, for those cases in which multiple documents need to be updated at once, there are UpdateMany() or UpdateManyAsync() options. 此外,对于需要同时更新多个文档的情况,还存在UpdateMany()UpdateManyAsync()选项。The UpdateMany() and UpdateManyAsync() methods match the documents in the Filter and will update all documents that match the filter requirements.UpdateMany()方法和updateManayAsync()方法与筛选器中的文档匹配,并将更新符合筛选器要求的所有文档。

Wrap Up总结

Update is an important operator in the CRUD world. Update是CRUD领域的一个重要运算符。Not being able to update things as they change would make programming incredibly difficult. 不能在事物发生变化时进行更新会使编程变得异常困难。Fortunately, C# and MongoDB continue to work well together to make the operations possible and easy to use. 幸运的是,C#和MongoDB继续很好地合作,使操作成为可能并且易于使用。Whether it's updating a student's grade or updating a user's address, Update is here to handle the changes. 无论是更新学生的成绩还是更新用户的地址,更新都可以处理这些更改。The code for the Create, Read, and Update operations can be found in this gist.创建读取更新操作的代码可以在这里找到。

We're winding down this C# Quick Start CRUD operation series with only one operation left to explore, Delete. 我们正在结束这个快速启动CRUD操作系列,只剩下一个操作需要探索,即删除In the next post, I'll show how to do that operation before we move onto the high power operations in MongoDB.在下一篇文章中,我将展示如何在MongoDB中进行高功率操作之前执行该操作。

Get started with an M0 cluster on MongoDB Atlas today. 现在就从MongoDB Atlas上的M0集群开始吧。It's free forever and you'll be able to work alongside this blog series.它永远是免费的,你将能够与这个博客系列一起工作。

Delete operations删除操作

This post will cover the last of the CRUD operations, Delete. 这篇文章将介绍最后的CRUD操作,删除If you've been following along with this series, I've been using sample data available in MongoDB Atlas, specifically the grades collection in the sample_training database. 如果您一直在关注本系列文章,那么我一直在使用MongoDB Atlas中提供的示例数据,特别是sample_training数据库中的grades集合。In the Create post, a new record was added to the data set.创建这篇文章中,向数据集中添加了一个新记录。

To continue along with the student story, let's take a look at how what would happen if the student dropped the course and had to have their grades deleted. 为了继续讲述学生的故事,让我们看看如果学生放弃了课程并不得不删除他们的成绩,会发生什么。Once again, the MongoDB driver for C# makes it a breeze. 再一次,MongoDB 驱动程序为C#带来了轻松。And, it provides both sync and async options for the operations.而且,它为操作提供了同步和异步选项。

Deleting Data删除数据

The first step in the deletion process is to create a filter for the document(s) that need to be deleted. 删除过程的第一步是为需要删除的文档创建筛选器。In the example for this series, I've been using a document with a student_id value of 10000 to work with. 在本系列的示例中,我使用了一个student_id值为10000的文档。Since I'll only be deleting that single record, I'll use the DeleteOne() method (for async situations the DeleteOneAsync() method is available). 因为我只删除那个记录,所以我将使用DeleteOne()方法(对于异步情况,可用DeleteOneAsync()方法)。However, when a filter matches more than a single document and all of them need to be deleted, the DeleteMany() or DeleteManyAsync method can be used.但是,当一个筛选器匹配多个文档并且需要删除所有文档时,可以使用DeleteMany()方法或DeleteManyAsync()方法。

Here's the record I want to delete.这是我要删除的记录。

{
  { "student_id", 10000 },
  { "scores", new BsonArray
    {
    new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
    new BsonDocument{ {"type", "quiz"}, {"score", 84.92381029342834 } },
    new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
    new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
    }
  },
  { "class_id", 483}
};

I'll define the filter to match the student_id equal to 10000 document:我将定义筛选器以匹配student_id等于10000的文档:

var deleteFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);

Assuming that we have a collection variable assigned to for the grades collection, we next pass the filter into the DeleteOne() method.假设我们为grades集合分配了一个collection变量,接下来我们将过滤器传递到DeleteOne()方法中。

collection.DeleteOne(deleteFilter);

If that command is run on the grades collection, the document with student_id equal to 10000 would be gone. 如果在grades集合上运行该命令,student_id等于10000的文档将消失。Note here that DeleteOne() will delete the first document in the collection that matches the filter. 请注意,DeleteOne()将删除集合中与筛选器匹配的第一个文档。In our example dataset, since there is only a single student with a student_id equal to 10000, we get the desired results.在我们的示例数据集中,由于只有一个学生的student_id等于10000,所以我们得到了期望的结果。

For the sake of argument, let's imagine that the rules for the educational institution are incredibly strict. 为了便于讨论,让我们想象一下,教育机构的规则极其严格。If you get below a score of 60 on the first exam, you are automatically dropped from the course. 如果你第一次考试成绩低于60分,你将被自动退学。We could use a for loop with DeleteOne() to loop through the entire collection, find a single document that matches an exam score of less than 60, delete it, and repeat. 我们可以使用带有DeleteOne()for循环遍历整个集合,找到一个匹配考试分数小于60的文档,删除它,然后重复。Recall that DeleteOne() only deletes the first document it finds that matches the filter. 回想一下DeleteOne()只删除它找到的第一个与筛选器匹配的文档。While this could work, it isn't very efficient as multiple calls to the database are made. 虽然这可以工作,但由于对数据库进行了多次调用,因此效率不高。How do we handle situations that require deleting multiple records then? 那么我们如何处理需要删除多个记录的情况呢?We can use DeleteMany().我们可以使用DeleteMany()

Multiple Deletes多次删除

Let's define a new filter to match the exam score being less than 60:让我们定义一个新的过滤器来匹配小于60的考试分数:

var deleteLowExamFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("scores",
     new BsonDocument { { "type", "exam" }, {"score", new BsonDocument { { "$lt", 60 }}}
});

With the filter defined, we pass it into the DeleteMany() method:定义好筛选器后,我们将其传递到deleteMany()方法:

collection.DeleteMany(deleteLowExamFilter);

With that command being run, all of the student record documents with low exam scores would be deleted from the collection.运行该命令后,所有考试分数低的学生记录文档都将从集合中删除。

Check out the gist for all of the CRUD commands wrapped into a single file.查看打包到一个文件中的所有CRUD命令的要点

Wrap Up总结

This C# Quick Start series has covered the various CRUD Operations (Create, Read, Update, and Delete) operations in MongoDB using basic BSON Documents. 这个C快速入门系列介绍了MongoDB 中使用基本BSON文档的各种CRUD操作(创建、读取、更新和删除)操作。We've seen how to use filters to match specific documents that we want to read, update, or delete. 我们已经了解了如何使用过滤器来匹配要读取、更新或删除的特定文档。This series has, thus far, been a gentle introduction to C Sharp and MongoDB.到目前为止,这个系列是对C#和MongoDB的一个温和的介绍。

BSON Documents are not, however, the only way to be able to use MongoDB with C Sharp. 然而,BSON文档并不是将MongoDB与C#协同使用的唯一方法。In our applications, we often have classes defining objects. 在我们的应用程序中,我们通常有定义对象的类。We can map our classes to BSON Documents to work with data as we would in code. 我们可以将类映射到BSON文档,以便像在代码中那样处理数据。I'll take a look at mapping in the next part of this C Sharp Quick Start series.我将在这个C#快速入门系列的下一部分中查看映射。

Get started with an M0 cluster on MongoDB Atlas today. 现在就从MongoDB Atlas上的M0集群开始吧。It's free forever and you'll be able to work alongside this blog series.它永远是免费的,你将能够与这个博客系列一起工作。