A simple call to the graph and text tutorial of moongodb in. Net

Time:2020-5-10

Preface

This article mainly introduces the method of moongodb call in. Net, and shares it for your reference and study. I won’t say much next, let’s take a look at the detailed introduction

The method is as follows:

1. Install. Net driver: install package mongodb.driver

2. Data insertion, linking databases

//New person test class
 public class Person
 {
  public long Id { get; set; }
  public int Age { get; set; }
  public string Name { get; set; }
  public int Height { get; set; }
  public TestPerson t1{ get; set; }
 }
 public class TestPerson {
  public string Name { get; set; }
 }
 public class ObjectPerson {
  public ObjectId Id { get; set; }
  public int Age { get; set; }
  public string Name { get; set; }
  public int Height { get; set; }
 }
MongoClient client = new MongoClient("mongodb://127.0.0.1");
 Imongodatabase database = client. Getdatabase ("testdb"); // equivalent to database
 Imoncollection < person > collection = database. Getcollection < person > ("persons"); // roughly equivalent to table
 Person p1 = new Person()
 {
 Id = 2,
 Name = "test1",
 Age = 29,
 Height=130
 };   
 Collection. Insertone (P1); // single insert also supports asynchronous methods. It is recommended to use asynchronous methods later. It's natural to be used!

When you go back to the client tool and refresh it, you can see the newly inserted data. Mongodb will automatically create “database” and “collection” (about equal to “table”). Mongodb uses ID as the primary key by default, so it is not necessary to explicitly specify that ID is the primary key.

There is no built-in “auto increment field” in mongodb. You can declare the ID as the objectid type (using mongodb. Bson) so that after insertion, the field will be assigned automatically.

//Multiple inserts
 Imoncollection < objectperson > Collection1 = database. Getcollection < objectperson > ("objectpersons"); // roughly equivalent to table
 List<ObjectPerson> persons = new List<ObjectPerson>() { new ObjectPerson() { Name = "test2", Age = 30, Height = 135 }, new ObjectPerson() { Name = "test3", Age = 31, Height = 140 } };
 collection1.InsertMany(persons);//Multiple inserts

Mongodb is saved in JSON, so it can also be directly inserted in JSON format, represented by bsondocument:


IMongoCollection<BsonDocument> dogs = database.GetCollection<BsonDocument>("Dogs");
string jsondata = "{id:8999,Age:81,Name:'japan',gender:true}";
BsonDocument p2 = BsonDocument.Parse(jsondata);
dogs.InsertOne(p2);

You can also insert objects with nested relationships, such as students and teachers. Note that there will be no inter table relationships. They are all stored in a collection. Note that they are different from relational databases.

Imoncollection < person > collection = database. Getcollection < person > ("persons"); // roughly equivalent to table
Person p1 = new Person()
{
 Id = 2,
 Name = "test1",
 Age = 29,
 Height=130,
 t1=new TestPerson() { Name="222"}
};   
 Collection. Insertone (P1); // single insert

3. Mongodb query

IMongoCollection<Person> collection = database.GetCollection<Person>("Persons");
var filter = Builders<Person>.Filter.Gt(p => p.Age,5);
Var filter1 = builders < person >. Filter. And (builders < person >. Filter. GT (P = > p.age, 5), builders < person >. Filter. EQ (P = > p.id, 1)); // and also or method
Var Filter2 = builders < person >. Filter. Where (P = > p.age > 5 & & p.id = = 1); // it is the same as the above writing method, but it is recommended to use the where method
 //General query
var result= collection.Find(filter).ToList();
foreach (var item in result)
{
 Console.WriteLine(item.Age + item.Name);
}

Besides GT, there are also GTE, in, lt, LTE, NE, Nin, near, nearsphere, or, where, and, not. Of course, the most common operation is where:

Asynchronous query

//Asynchronous query
 using (IAsyncCursor<Person> personsCursor = await collection.FindAsync<Person>(filter)) {
 While (personscursor. Movenextasync(). Result) // get the next set of data, which is equivalent to whether there is a pointer. Mongodb actually returns a group, unlike SQL, which fetches every time
 {
 IEnumerable < person > items = personalscursor. Current; // returns the data of the current group
 foreach (var item in items)
 {
  Console.WriteLine(item.Age + item.Name);
 }
 }
 //If the amount of data is small, you can directly tolist
 var results = personsCursor.ToList();
}

Why does findasync not directly return to the set, but to return to a set after MoveNext? Because the amount of data returned may be very large, mongodb downloads in batches. After downloading a batch, it performs the get ﹐ more operation to return to the next batch. You can set the size of each batch through the batchsize of the findoptions parameter.

If you confirm that the amount of data returned is small, you can var PS = await personalscursor. Tolitasync() (or toenumerable(), etc.) return all the data at once. There are any, first, firstordefault, and asynchronous operations. Note that queries in mongodb are case sensitive.

4. Paging query

//Pagination
FindOptions<Person, Person> findop = new FindOptions<Person, Person>();
Findop. Limit = 3; // take up to a few
Findop. Skip = 2; // skip several
Findop. Sort = builders < person >. Sort. Ascending (P = > p.age). Ascending (P = > p.name); // sort
using (var cursor = collection.FindAsync(filter, findop).Result)
{
 var items = cursor.ToList();
 foreach (var item in items)
 {
 Console.WriteLine(item.Age + item.Name);
 }
}

Specify the sorting rule findop. Sort = builders < person >. Sort. Ascending (P = > p.age). Ascending (P = > p.name);

5. JSON format access

//JSON format fetching
IMongoCollection<BsonDocument> bsonDoc = database.GetCollection<BsonDocument>("Persons");
var filter4 = Builders<BsonDocument>.Filter.Gt("Age", 5);
using (var persons=await bsonDoc.FindAsync(filter4)) 
{
 foreach (var item in await persons.ToListAsync())
 {
 Console.WriteLine(item.GetValue("Name").AsString);
 }
}

6. Update update operation

IMongoCollection<Person> upPersons = database.GetCollection<Person>("Persons");
Var upfilter = builders < person >. Filter. Where (P = > p.age > 20); // filter criteria
Var update = builders < person >. Update. Set (C = > c.name, "test2"); // update the condition, update the name to test2
upPersons.UpdateMany(filter, update);

7. Delete delete operation


IMongoCollection<Person> teachers = database.GetCollection<Person>("Persons");
var deletefilter = Builders<Person>.Filter.Where(p => p.Id == 1);
teachers.DeleteMany(deletefilter);

There are few opportunities to use update. If you use update frequently, it may mean that you are using it wrong. Don’t think about join, group by, or the scene is wrong!

8. Mongodb application scenario

Log recording system; storage of equipment monitoring data; order receiving of hungry delivery rider; storage of commodity and business information; website comment information; storage of third-party data crawled by reptiles;

But don’t use mongodb for such key information as orders, financial transactions, game equipment, etc;

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.