net核心怎么使用MongoDB

  介绍

这篇文章主要介绍”。网络核心怎么使用MongoDB”,在日常操作中,相信很多人在。网络核心怎么使用MongoDB问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”。网络核心怎么使用MongoDB”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

<强>前言

MongoDB是由c++语言编写的,是一个基于分布式且面向文档存储的开源数据库系统。

下载地址:

https://www.mongodb.com/download-center/community

在。Net核心中使用需要引入核心包MongoDB。司机

<>强添加数据:

//与Mongodb建立连接   MongoClient  client =, new  MongoClient (“mongodb://127.0.0.1");//获得数据库,没有则自动创建   IMongoDatabase  db =, client.GetDatabase (“db1");//拿到集合(表)   IMongoCollection (“Student");   var  data =, new 学生();   时间=data.id  1;   时间=data.name “江北“;   时间=data.age  22;   时间=data.remarks “暂无”;//添加一条数据   student.InsertOne(数据);

在图形化界面中查看一下

。网络核心怎么使用MongoDB

。网络核心怎么使用MongoDB

MongoDB默认用身份证做主键,因此不会显式的指定id是主键.Mongdb中没有内置“自增字段“,可以把id声明为ObjectId类型,这样插入以后就自动给字段赋值。

例如,建一个类:

public  class 学校   {   ,public  ObjectId  id {组,得到,,,}   ,public  string  name {组,得到,,,}   ,public  string  address {组,得到,,,}   }//需引入命名空间,using  MongoDB.Bson;

。网络核心怎么使用MongoDB

。网络核心怎么使用MongoDB

当然学校对象之后多加或者去掉一个字段都行.Mongodb是用Json保存的,因此也可以直接用Json格式插入,可用BsonDocument对象作为泛型对象。

//与MongoDB建立连接   MongoClient  client =, new  MongoClient (“mongodb://127.0.0.1");//获得数据库,没有则自动创建   IMongoDatabase  db =, client.GetDatabase (“db1");//拿到集合(表)   IMongoCollection (“School");   db.GetCollection (“School");   var  json =,“{id: 1、名称:& # 39;xx学校& # 39;,地址:& # 39;xxx路xx号& # 39;,备注:& # 39;暂无! & # 39;}“;   BsonDocument  bsons =, BsonDocument.Parse (json);

。网络核心怎么使用MongoDB

学生和学校是有对应关系的,我们可以添加有嵌套关系类型的对象

public  class 学生   {   ,public  int  id {组,得到,,,}   ,public  string  name {组,得到,,,}   ,public  int  age {组,得到,,,}   ,public  string  remarks {组,得到,,,}   ,public  School  School {组,得到,,,}   } //与Mongodb建立连接   MongoClient  client =, new  MongoClient (“mongodb://127.0.0.1");//获得数据库,没有则自动创建   IMongoDatabase  db =, client.GetDatabase (“db1");//拿到集合(表)   IMongoCollection (“Student");   Student  student1 =, new 学生();   student1.id =, 2;   时间=student1.name “北晚舟“;   时间=student1.age  22;   时间=student1.remarks “暂无”;   School  School =, new 学校();   时间=school.name “xxxSchool";   时间=school.address “xxxAddress";   时间=student1.School 学校;   student.InsertOne(学生1);

。网络核心怎么使用MongoDB

<强>数据查询:

//与MongoDB建立连接   MongoClient  client =, new  MongoClient (“mongodb://127.0.0.1");//获得数据库,没有则自动创建   IMongoDatabase  db =, client.GetDatabase (“db1");//拿到集合(表)   IMongoCollection

net核心怎么使用MongoDB