dotnet core use MangoDB
安装MangoDB
同样我这边再次使用Docker, 方便快捷:
# 拉取镜像
docker pull mongo
# 运行镜像
docker run -d -p 37017:27017 --name mongoapp mongo
具体使用
基本代码使用的演示如下:
class Program
{
static void Main(string[] args)
{
//建立连接
var client = new MongoClient("mongodb://127.0.0.1:37017");
//建立数据库
var database = client.GetDatabase("foo");
//建立collection
var collection = database.GetCollection<BsonDocument>("bar");
//为方便测试, 清除部分历史记录
var df = Builders<BsonDocument>.Filter.Gte("counter", 0);
collection.DeleteMany(df);
//插入单条记录
var document = new BsonDocument
{
{ "name", "MongoDB" },
{ "type", "Database" },
{ "count", 1 },
{ "info", new BsonDocument
{
{ "x", 203 },
{ "y", 102 }
}}
};
collection.InsertOne(document);
//异步插入
//await collection.InsertOneAsync(document);
//插入多条记录
// generate 100 documents with a counter ranging from 0 - 99
var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i));
collection.InsertMany(documents);
//异步插入
//await collection.InsertManyAsync(documents);
//计数
var count = collection.Count(new BsonDocument());
Console.WriteLine("Count:{0}", count);
//异步计数
//var count = await collection.CountAsync(new BsonDocument());
//查询
//首条记录
var query1 = collection.Find(new BsonDocument()).FirstOrDefault();
Console.WriteLine("Query1:{0}", query1);
//条件查询
var filter = Builders<BsonDocument>.Filter.Eq("counter", 71);
var query2 = collection.Find(filter).FirstOrDefault();
Console.WriteLine("Query2:{0}", query2);
//全部记录
var query3 = collection.Find(new BsonDocument()).ToList();
Console.WriteLine("Query3:{0}", query3.ToJson());
Console.WriteLine("Hello World!");
}
}
项目源码在Gitee.(不好意思, mongo都拼写错了, 不改了)
更多使用请参考官方文档:http://mongodb.github.io/mongo-csharp-driver/2.2/getting_started/quick_tour/
原创文章,转载请注明来源