MongoDB基本操作
public partial class Form1 : Form
{
//参考:https://mp.weixin.qq.com/s/t3ye73k7n2ffFnddbv8oPg
//https://www.mongodb.com/docs/drivers/csharp/current/usage-examples/findOne/
//https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzkzNDQzNTAzNw==&action=getalbum&album_id=2746018263371628544&scene=173&from_msgid=2247483817&from_itemidx=1&count=3&nolastread=1#wechat_redirect
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
HashSet<string> t = new HashSet<string>();
t.Add("22");
t.Add("22");
t.Add("222");
int count = t.Count;
}
private async void button1_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/
BsonDocument filter = new BsonDocument(); //查询全部
using (var cursor = await collection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (BsonDocument document in batch)
{
this.textBox1.Text = (document.ToJson());
}
}
}
}
private void button5_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
var filter = Builders<BsonDocument>.Filter.Eq("name", "雷俊强");
List<BsonDocument> r = collection.Find(filter).ToList();
}
private async void button2_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
BsonDocument d = new BsonDocument();
// d.Add("name", "有数");
// d.Add("age", 120);
// collection.InsertOne(d);
d = new BsonDocument();
d.Add("_id", Guid.NewGuid().ToString().Replace("-", "")); //_id可以不用写,数据库会给默认值,且比这个字符串短一些
d.Add("name", "有数");
d.Add("age", 120);
await collection.InsertOneAsync(d);
}
private void button3_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
var filter = Builders<BsonDocument>.Filter.Eq("name", "有数");
var setvalue = Builders<BsonDocument>.Update.Set("name", "心里有数");
UpdateResult r = collection.UpdateMany(filter, setvalue); //返回值有是否成功,和更新的记录数量
}
private void button4_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
//eq表示相等比较,其他比较符参考以下
//https://mp.weixin.qq.com/s?__biz=MzkzNDQzNTAzNw==&mid=2247483754&idx=1&sn=f53feec63287abefd0d936da7362321f&chksm=c2bc00d8f5cb89ce76316b2ab7201d438eaa27f389838ae1c84648e11967e1763fded0b18774&scene=178&cur_album_id=2746018263371628544#rd
var filter = Builders<BsonDocument>.Filter.Eq("name", "心里有数");
DeleteResult r = collection.DeleteMany(filter); //返回值有是否成功,和更新的记录数量
}
private void button6_Click(object sender, EventArgs e)
{
// https://www.cnblogs.com/lipan/archive/2011/03/21/1989409.html
//小文件可以直接放在一般Document中,最大16M,参考上面链接
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
BsonDocument d = new BsonDocument();
d["img"] = System.IO.File.ReadAllBytes("视频监控.png");
d["name"] = "文件";
collection.InsertOne(d);
}
private void button7_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tb2");
BsonDocument d = new BsonDocument();
d["name"] = "文件";
List<BsonDocument> r = collection.Find(d).ToList();
byte[] buf = (byte[])(r[0]["img"]);
System.IO.File.WriteAllBytes("视频监控1.png", buf);
}
private async void button9_Click(object sender, EventArgs e)
{
//参考:https://www.sohu.com/a/457367447_468635
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
//var bucket = new GridFSBucket(database); //不指定名称,则是默认名fs
var bucket = new GridFSBucket(database, new GridFSBucketOptions { BucketName = "fsTest" }); //指定存储桶的名称,没有的话会自动创建
string file = "hp-socket-5.9.1-lib-win.zip";
bucket.UploadFromStream(file, new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read));
}
private async void button8_Click(object sender, EventArgs e)
{
IMongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
IMongoDatabase database = client.GetDatabase("test");
//var bucket = new GridFSBucket(database); //不指定名称,则是默认名fs
var bucket = new GridFSBucket(database, new GridFSBucketOptions { BucketName = "fsTest" }); //指定存储桶的名称,没有的话会自动创建
string file = "hp-socket-5.9.1-lib-win---.zip";
using (var fs = new FileStream(file, FileMode.Create))
{
//按文件名下载,也可按id下载等
//只一个文件名,可以上传多个版本,下载时也可指定版本,参考:https://www.sohu.com/a/457367447_468635
await bucket.DownloadToStreamByNameAsync("hp-socket-5.9.1-lib-win.zip", fs);
}
}
}
}
//https://www.jb51.net/article/250784.htm
////4.获取数据集 collection;BsonDocument是在数据没有预先定义好的情况下使用的。
//IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("runoob1");
////5.插入一条数据;
//var document = new BsonDocument { { "id", 2 }, { "name", "aa" } };
//collection.InsertOne(document);
////6.查询数据1
//var res = collection.Find(new BsonDocument()).ToList(); //查询整个数据集
//foreach (var item in res)
//{
// Console.WriteLine(item);
//}
////6.查询数据2
//var res_a = collection.Find(new BsonDocument()).FirstOrDefault(); //查询当前数据集的第一条数据,没有则返回null
//Console.WriteLine(res_a);
////6.升序降序查询3:
//var sort_ascending = Builders<BsonDocument>.Sort.Ascending("id"); //根据id升序
//var sort_descending = Builders<BsonDocument>.Sort.Descending("id"); //根据id降序
//var res_c = collection.Find(Builders<BsonDocument>.Filter.Lt("id", 10) & Builders<BsonDocument>.Filter.Gte("id", 2)).Limit(50).Sort(sort_ascending).ToCursor(); //查询id小于10,大于2的数据
//foreach (var item in res_c.ToEnumerable())
//{
// Console.WriteLine(item);
//}
////7.更新数据,更新支持添加新的field, 如:
//collection.UpdateMany(Builders<BsonDocument>.Filter.Eq("id", 2), Builders<BsonDocument>.Update.Set("name", "hello")); //将id字段为2的名字都改为“hello”;
////8.删除
//collection.DeleteMany(Builders<BsonDocument>.Filter.Eq("id", 2));