C# Asp.net中简单操作MongoDB数据库(一)

时间:2024-01-12 22:46:02

需要引用MongoDB.Driver.dll、MongoDB.Driver.core.dll、MongoDB.Bson.dll三个dll。

1、数据库连接:

public class MongoDb
{
//方式一
//private static readonly string connStr = "mongodb://myAdmin:123456@localhost";
//private static readonly string dbName = "myTest"; //方式二(myTestAdmin用户只可访问数据库myTest)
private static readonly string connStr = "mongodb://myTestAdmin:123456@localhost/myTest"; private static IMongoDatabase db = null; private static readonly object lockHelper = new object(); private MongoDb() { } public static IMongoDatabase GetMongoDb()
{
if (db == null)
{
lock (lockHelper)
{
if (db == null)
{
//方式一
//var client = new MongoClient(connStr);
//db = client.GetDatabase(dbName); //方式二(myTestAdmin用户只可访问数据库myTest)
var url = new MongoUrl(connStr);
MongoClientSettings mcs = MongoClientSettings.FromUrl(url);
mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds();
var client = new MongoClient(mcs);
db = client.GetDatabase(url.DatabaseName);
}
}
}
return db;
}
}

2、插入操作:

class Program
{
static void Main(string[] args)
{
IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //插入
var document = new BsonDocument
{
{ "name", "Liming" },
{ "age", "" },
{ "score", new BsonDocument
{
{ "yuwen", },
{ "shuxue", },
{ "yingyu", }
}}
};
collection.InsertOne(document); Console.ReadKey();
}
}

Robomongo中查看结果:

C# Asp.net中简单操作MongoDB数据库(一)

3、查询操作:

class Program
{
static void Main(string[] args)
{
IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //查询
var document = collection.Find(new BsonDocument()).FirstOrDefault();
Console.WriteLine(document.ToString()); Console.ReadKey();
}
}

4、更新操作:

class Program
{
static void Main(string[] args)
{
IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //更新
var filter = Builders<BsonDocument>.Filter.Eq("age", "");
var update = Builders<BsonDocument>.Update.Set("age", "");
collection.UpdateOne(filter, update); Console.ReadKey();
}
}

5、删除操作:

 class Program
{
static void Main(string[] args)
{
IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //删除
var filter1 = Builders<BsonDocument>.Filter.Eq("age", "");
collection.DeleteOne(filter1); Console.ReadKey();
}
}

参考:http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/

上面操作的集合类型都是BsonDocument,

下面可以自定义实体类,mongodb可以直接返回对应自定义类的集合或者对象:

C# Asp.net中简单操作MongoDB数据库(二)

相关文章