Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The basic use of MongoDB's C # driver

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "the basic use of MongoDB's C#driver". In daily operation, I believe many people have doubts about the basic use of MongoDB's C#driver. The editor consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "the basic use of MongoDB's C#driver"! Next, please follow the small series to learn together!

When using C#drivers, add references to "MongoDB.Bson.dll" and "MongoDB.Driver.dll" to your project. Add the following two using statements to your code:

using MongoDB.Bson;using MongoDB.Driver;

database connection

To establish a database connection, you must know the address, port and other information of the server. All of this information is represented by connection strings. The MongoDB connection string format is as follows:

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][? options]]

Let's look at what each field in the connection string means:

mongodb://: This is the prefix of the MongoDB connection string

username:password(Optional): Optional, indicates login username and password, used to complete user security authentication

hostN: Must specify at least one host, indicating the MongoDB instance to which to connect

portN(Optional): Optional, default to 27017

database(Optional): If username:password@ is specified, connect and verify login to the specified database. If not specified, the admin database is opened by default.

options(Optional): Optional, if you do not use/database, you need to add/before it. All join options are key-value pairs name=value, separated by∨(semicolon)

Here, using the example from the article "MongoDB Administration," test1 and test2 have their own users. When accessed using the following connection string, you get correct validation because "Will1:Will1" has read and write permissions on test1. If you access the test2 database instead, you get an exception output of "Invalid credentials for database 'test2'."

string connectionStr = "mongodb://Will1:Will1@localhost";MongoClient client = new MongoClient(connectionStr);MongoServer server = client.GetServer();MongoDatabase db = server.GetDatabase("test2");MongoCollection collection = db.GetCollection("student");try{ Console.WriteLine("db name is: " + db.Name); Console.WriteLine("collections name is: " + collection.Name); Console.WriteLine("{0} items in this collection", collection.Count());}catch (Exception e){ Console.WriteLine(e.Message);}

As you can see from the code above:

How to get client and server objects

string connectionStr = "mongodb://Will1:Will1@localhost";MongoClient client = new MongoClient(connectionStr);MongoServer server = client.GetServer();

How to get database and collection objects

MongoDatabase db = server.GetDatabase("test2");MongoCollection collection = db.GetCollection("student");

BsonDocument object model

Before we begin our introduction to add, delete, and search, let's look at the BsonDocument object model.

In MongoDB collection, each document can be treated as a Bson(Binary JSON) object, so there is a BsonDocument type in the driver, which can generate a document in the following way and add key/value pairs through the Add method. BsonDocument objects generated in this way can be inserted directly into a collection.

BsonDocument student1 = new BsonDocument();student1.Add("sid", 10);student1.Add("name", "Will10");student1.Add("gender", "Male");student1.Add("age", 26);

In MongoDB, there are two ways for users to manipulate collections:

Through the BsonDocument object model

By custom type

We have already introduced the BsonDocument object, but we can also use our own custom types here. For example, we can define a Student type and insert objects of that type into a collection.

public class Student{ public ObjectId _id; public int sid; public string name; public string gender; public int age;}

Note: The Id field must be present when using custom types.

Both of the above methods can be used, and each has its own advantages. By customizing the type, you can make the documents in the collection have a more uniform pattern; by using the BsonDocument method, you can support more document patterns, that is, if the documents in a collection have various patterns, then the BsonDocument method will be more flexible.

insert data

For data insertion, we can use the "Insert()" method in collection. Two records were inserted below. It can be inserted as a BsonDocument object or as a custom type.

By means of BsonDocument, users can freely define the format of documents. For example, a "hobby" field has been added (Ps: this is not recommended, it can be cumbersome for document queries).

BsonDocument student1 = new BsonDocument();student1.Add ("sid", 10);student1.Add ("name", "Will10");student1.Add ("gender", "Male");student1.Add ("age", 26);student1.Add ("hobby", new BsonArray() { "swimming","reading"});collection.Insert (student1); Student2 = new Student();student2.age = 27;student2.name = "Wilber";student2.gender = "Male";collection.Insert(student2); query data

MongoDB driver supports three query methods.

QueryDocument

Query in this way is similar to our conditional query in MongoDB shell. For example, query students older than 20

QueryDocument queryDocument = new QueryDocument("age", new QueryDocument("$gt",20));foreach (var student in collection.Find(queryDocument)){ Console.WriteLine(student);}

When there are multiple query conditions, for example, male students older than 20 are queried.

QueryDocument queryDocument = new QueryDocument(new BsonElement("age", new QueryDocument("$gt", 20)), new BsonElement("gender","Male"));Query Builder

Query Builder is a more concise way, when querying in this way, we need to use builder in driver to generate query. So, quote the following using statement

using MongoDB.Driver.Builders;

Students older than 20 can be queried by using the following sentence

var query = Query.GT("age", 20); foreach (var student in collection.Find(query)) { Console.WriteLine(student); }

Search for male students older than 20

var query = Query.And(Query.GT("age", 20), Query.EQ("gender", "Male"));

Of course, we can also perform strongly typed queries, but this query has a prerequisite,"the fields in the document must be a subset of the custom type fields, that is, the document can be converted to a specific type." For example, if we insert a document with the key "hobby" earlier, we will generate an exception indicating that the Student type does not have the field hobby if we use the following method:

var query = Query.GT(e => e.age, 20);foreach (var student in collection.FindAs(query)){ Console.WriteLine(student);}

In this case, you can query using the BsonDocument type. One thing I don't understand is why Query doesn't report errors when using Student strong types.

var query = Query.GT(e => e.age, 20);foreach (var student in collection.FindAs(query)){ Console.WriteLine(student); LINQ Support

After the 1.8 release of the driver, the official driver can support LINQ operation. We only need to use the following using statement to support LINQ queries.

using MongoDB.Driver.Linq;

Therefore, you can query students older than 20, or you can do it in the following way (note that you also need to ensure that all documents can be converted to Student type)

var linquery = from e in collection.AsQueryable() where e.age > 20 select e;var linquery1 = collection.AsQueryable().Where(e => e.age > 20);

There are many LINQ query operations in MongoDB documentation, please see LINQ section of MongoDB documentation

update data

There are two ways to update a document: replace the entire document with the Save method, or update part of the document with the Update method.

For example, find the document with sid 9 and name Will9 and update the age field to 27

Save method var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9"));BsonDocument Will9 = collection.FindOne(query);if (Will9 != null){ Will9["age"] = 27; collection.Save(Will9);}Update method var query = Query.And(Query.EQ("sid", 9), Query.EQ("name", "Will9"));var update = Update.Set("age", 27);collection.Update(query, update); delete data

Deleting data is relatively simple.

Delete documents with specific conditions:

var query = Query.EQ("sid", 9);collection.Remove(query);

Delete all documents:

collection.RemoveAll(); At this point, the study of "Basic use of MongoDB C#driver" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report