MongoDB与c#(一)简单例子
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Text; 7 8 namespace ConsoleApplication8 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 15 //数据库连接字符串 16 17 //带有用户名,密码的如下写法,不带的则直接ip+端口就可以 18 const string strconn = "mongodb://liyang:liyang@192.168.1.211:27017"; 19 20 //数据库名称 21 22 const string dbName = "liyang"; 23 24 //创建数据库链接 25 26 MongoServer server = MongoDB.Driver.MongoServer.Create(strconn); 27 28 //获得数据库cnblogs 29 30 MongoDatabase db = server.GetDatabase(dbName); 31 32 MongoCollection cl = db.GetCollection("Users"); 33 34 var query = cl.FindAllAs<Users>().ToList(); 35 36 foreach (var item in query) 37 { 38 Console.WriteLine("name:" + item.Name + " Sex:" + item.Sex); 39 } 40 41 Console.ReadKey(); 42 43 //for (int i = 0; i < 10000; i++) 44 //{ 45 // cl.Insert<Users>(new Users 46 // { 47 // Name = "ly"+i, 48 // Sex="男人" 49 // }); 50 // Console.WriteLine(i.ToString()); 51 //} 52 } 53 } 54 public class Users 55 { 56 57 public ObjectId _id;//BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId 58 59 public string Name { get; set; } 60 61 public string Sex { set; get; } 62 63 } 64 }
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//数据库连接字符串
//带有用户名,密码的如下写法,不带的则直接ip+端口就可以
const string strconn = "mongodb://liyang:liyang@192.168.1.211:27017";
//数据库名称
const string dbName = "liyang";
//创建数据库链接
MongoServer server = MongoDB.Driver.MongoServer.Create(strconn);
//获得数据库cnblogs
MongoDatabase db = server.GetDatabase(dbName);
MongoCollection cl = db.GetCollection("Users");
var query = cl.FindAllAs<Users>().ToList();
foreach (var item in query)
{
Console.WriteLine("name:" + item.Name + " Sex:" + item.Sex);
}
Console.ReadKey();
//for (int i = 0; i < 10000; i++)
//{
// cl.Insert<Users>(new Users
// {
// Name = "ly"+i,
// Sex="男人"
// });
// Console.WriteLine(i.ToString());
//}
}
}
public class Users
{
public ObjectId _id;//BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId
public string Name { get; set; }
public string Sex { set; get; }
}
}
个人博客地址:http://www.blog.liyang.love