首页 > 数据库 >MongoDB基本操作

MongoDB基本操作

时间:2023-01-31 15:56:31浏览次数:65  
标签:database MongoDB collection client new var 基本操作 id


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));

标签:database,MongoDB,collection,client,new,var,基本操作,id
From: https://www.cnblogs.com/81/p/17079436.html

相关文章

  • Mongodb的安装部署
    它是由C++编写的分布式文档数据库。内部使用类似于Json的bson格式。官网文档https://docs.mongodb.com/中文手册https://www.w3cschool.cn/mongodb/安装https://www.m......
  • Python操作Mongodb
    客户端客户端连接$bin/mongo.exeMongoDBshellversionv3.6.13help打开帮助showdbs#查看当前有哪些库useblog#有就切换过去,没有就创建后切换过去。......
  • mongodb的安装与部署
    简介MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的......
  • 自从学习了MongoDB高可用,慢慢的喜欢上了它,之前确实冷落了
    大家好,我是哪吒,最近项目在使用MongoDB作为图片和文档的存储数据库,为啥不直接存MySQL里,还要搭个MongoDB集群,麻不麻烦?让我们一起,一探究竟,继续学习MongoDB高可用和片键策略,实......
  • Spring Data MongoDB 启动 WARN
    告警内容为2023-01-2821:49:45.148WARN[post-svr,,]60625---[main]o.s.data.convert.CustomConversions:Registeringconverterfromclassj......
  • 5天玩转MySQL:数据库概念、SQL介绍、数据库和数据表基本操作、字符表
    数据库概念数据库(Database)是按照数据结构来组织、存储和管理数据的建立在计算机存储设备上的仓库。数据库:存储数据的仓库数据库分类网络数据库网络数据库是指把数据库技术......
  • 手把手教你搭建mongodb分片集群
    本章用的自己的电脑win10系统 因为工作上的环境也是win的 就没在虚拟机上玩 (ps:其实上面环境都大同小异)在MongoDB(版本6.xx)中,分片是指将collection分散存储到不同......
  • Mongodb多租户功能实现
    importcom.mongodb.client.MongoClient;importcom.mongodb.client.MongoDatabase;importlombok.extern.slf4j.Slf4j;importorg.springframework.data.mongodb.core......
  • SqlServer 与 MySQL 基本操作语句对比
    继上篇 ​​MySQL基本操作语句​​ 后,个人测试和补充了 SqlServer与MySQL的 基本操作语句对比,主要是对比SQL命令的一些差异,不作更多说明。(由于mysql没有系统学习过......
  • MongoDB 基础(二)mongodb 与 T-SQL 对比
    SQLTerms/ConceptsMongoDBTerms/ConceptsdatabasedatabasetableCollection(集合)rowdocument(文档)columnKey(键)ValueValue(值)indexindextablejoinsembeddeddocumentsandlin......