MongoDB初步(2)_基本语法命令常用语法命令

6 篇文章 0 订阅
3 篇文章 0 订阅

前面已经介绍了MongoDB的安装和基本配置服务过程,接下来就开始我们的正式工作,真正用代码去操作我们的数据库,我这儿将代码分为两种,下面做分别介绍

这里我插一句,第一篇好像有些地方写漏了,图片我都有code补上了,不好意思哈害羞

(1):shell中基本命令操作。根据自己亲身体验,服务搭建好了后,输入命令(show dbs)会出现默认的几个库,这里我就admin库做尝试。

首先输入命令:use admin

然后:我们建一个表并完成数据插入(备注,这里插入数据和建表是一步完成的,也就是说在建表的过程中插入了数据;如果你见的表已经存在,则不会新建表,直接插入数据),此时我需要输入命令(我这里建表的表名是“person”):db.person({"name":“jolin”,“age”:35}),然后回车就完成了一条数据插入(同时完成了person表的创建)。然后下面就是基本的数据操作,我这里整理了一下,应该是相当清楚了,下面发出来和大家分享(这些都是我试验过的,个人觉得应该是没有什么错了,只要会写T-SQL语句的朋友都知道是什么意思,后面的SQL语句都是我手写的,可能会因为写快了有错误,但这都不影响的):

db.person.insert({"name":"lucky","age":22})  == insert into person values("lucky", 22);--person是表(name和age是字段)
db.person.find() ==  select * from person  --为了显示更清晰,可以这样写:db.person.find().pertty()
db.person.update({"name":"lucky"},{"name":"lucky","age":1234})  == update person set name = 'lucky', age = 1234 where name = 'lucky'
db.person.remove({"name":"lucky})  == delete person where name = 'lucky'
db.person.find({"age":{$gt:40}})  == select * from person where age > 40 -- $gte相当于>=,$lt相当于<,$lte相当于<=,$ne相当于<>就是不等于
db.person.find({"age":{$in[35,56]}})  == select * from person where age in (35, 56)
db.person.find({"name":"lucky","age":35})  == select * from person where name = 'lucky' and age = 35
db.person.find({$or:[{"name":"lucky"},{"name":"Jolin"}]}) == select * from person where name = 'lucky' or name = 'Jolin'
db.person.find({$where:function(){ return this.name == 'lucky'}})  == select * from person where name = 'lucky'
db.person.update({"name":"lucky"},{$inc:{"age":34}})  == update person set age = (age + 30) where name = 'lucky'
db.person.update({"name":"Jolin"},{$set:{"age":35}})  == update person set age = 35 where name = 'Jolin'
db.person.update({"name":"lucky"},{$inc:{"age":34}},true)  == 如果数据库查到有这条数据,则直接修改,没有的话就增加一条
db.person.update({"name":"lucky"},{$set:{"age":1019}},true,true)  ==批量更新:where name = 'lucky'
db.person.count()  == select count(*) from person
db.person.count({"name":"lucky"})  == select count(*) from person where name = 'lucky'
db.person.distinct("name")  == select distinct name from person
db.person.ensureIndex({"name":1})  ==  强person表中name字段设为索引,按照升序排列,如果为-1,则表示降序排列
db.person.ensureIndex({"name":1},{"unique":true})  == 建立name字段为唯一索引

......

db.createUser( { "user" : "luckily",
                 "pwd": "123456",
                 "customData" : { employeeId: 12335 },
                 "roles" : [ { role: "userAdmin", db: "admin" },
                             { role: "readAnyDatabase", db: "admin" },
                             "readWrite"
                             ] },
               { w: "majority" , wtimeout: 5000 } )

(2):上面的我就不多说了,下面介绍我们的最终目的,C#代码中运用MongoDB进行数据的基本操作

啥也不说了,直接贴代码

a.先发图(图中的红色的线框圈住student表中有几条数据)

b.直接贴代码咯

1.我先创建了一个student类如下

public class student
    {
        //public Object id { set; get; }
        public string name { set; get; }
        public int age { set; get; }
        public int num { set; get; }
        public student(string name, int age, int num)
        {
            this.name = name;
            this.age = age;
            this.num = num;
        }
        public student() { }
    }

2.然后我创建了一个MongoHelper类(基本数据操作)

public static class MongoHelper
    {
        public static string connectionString = "mongodb://localhost";
        private static string databaseName = "admin";        

        /// <summary>
        /// 查询(测试成功)
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static MongoCursor<BsonDocument> Search(string collectionName,IMongoQuery query)
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase dbs = server.GetDatabase(databaseName);
            MongoCollection<BsonDocument> collection = dbs.GetCollection<BsonDocument>(collectionName);
            try
            {
                if(query == null)
                {
                    return collection.FindAll();
                }
                else
                {
                    return collection.Find(query);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("查询异常:" + ex.Message.ToString());
                server.Disconnect();
                return null;
            }
            finally
            {
                server.Disconnect();
            }
        }

        /// <summary>
        /// 新增数据(测试成功)
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="document"></param>
        /// <returns></returns>
        public static bool AddData(string collectionName, BsonDocument document)
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase dbs = server.GetDatabase(databaseName);
            MongoCollection<BsonDocument> collection = dbs.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.Insert(document);
                server.Disconnect();
                return true;
            }
            catch(Exception ex)
            {
                server.Disconnect();
                Console.WriteLine("添加出错了:" + ex.Message.ToString());
                return false;
            }
        }

        /// <summary>
        /// 修改(测试成功)
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>
        /// <param name="updates"></param>
        /// <returns></returns>
        public static bool UpdateData(string collectionName, IMongoQuery query,IMongoUpdate updates)
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase dbs = server.GetDatabase(databaseName);
            MongoCollection<BsonDocument> collection = dbs.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.Update(query, updates);
                server.Disconnect();
                return true;
            }
            catch(Exception ex)
            {
                server.Disconnect();
                Console.WriteLine("修改异常:" + ex.Message.ToString());
                return false;
            }
        }

        /// <summary>
        /// 删除数据(测试成功)
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static bool DeleteData(string collectionName, IMongoQuery query)
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase dbs = server.GetDatabase(databaseName);
            MongoCollection<BsonDocument> collection = dbs.GetCollection<BsonDocument>(collectionName);
            try
            {
                collection.Remove(query);
                server.Disconnect();
                return true;
            }
            catch(Exception ex)
            {
                server.Disconnect();
                Console.WriteLine("删除异常:" + ex.Message.ToString());
                return false;
            }
        }
    }
3.基本调用(相当于DAL层)

public class MongoDBDB
    {
        private static string tableUser = "student";  

        public void Test()
        {
            string connString = "mongodb://luckily:123456@localhost";
            MongoClient mct = new MongoClient(connString);
            MongoServer msr = mct.GetServer();
            MongoDatabase mde = msr.GetDatabase("test");
            MongoCollection<BsonDocument> collection = mde.GetCollection("studenasdft");
            try
            {
                Console.WriteLine("mde.name is:" + mde.Name);
                Console.WriteLine("collection.name is:" + collection.Name);
                Console.WriteLine("{0} in this collection!!", collection.Count());
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }

        public void Test2()
        {
            #region    测试成功代码
            IMongoQuery query = Query.And(Query.EQ("age", 35));
            List<student> list = new List<student>();
            list = Search(query).ToList();
            //student stu = new student();
            //stu.name = "Butterfly";
            //stu.age = 18;
            //stu.num = 1019;
            //BsonDocument dom = new BsonDocument
            //{
            //    {"name", stu.name},
            //    {"age", stu.age},
            //    {"num", stu.num}
            //};
            //MongoHelper.AddData(tableUser, dom);            
            //IMongoQuery query = new QueryDocument("age", 19);
            //MongoHelper.DeleteData(tableUser, query);
            //IMongoQuery query = new QueryDocument("name", "xiaoran");
            //IMongoUpdate updata = Update.Set("age", 169).Set("num", 4444);
            //MongoHelper.UpdateData(tableUser, query, updata);
            #endregion

            
        }

        private IEnumerable<student> Search(IMongoQuery query)
        {
            foreach (BsonDocument document in MongoHelper.Search(tableUser, query))
            {
                yield return new student(document["name"].AsString, document["age"].AsInt32, document["num"].AsInt32);
            }
        }
    }
4.最后:main方法调用

MongoDBDB mdb = new MongoDBDB();
            mdb.Test2();
            Console.ReadKey();

上面的增删改查我都是测试成功后才把代码贴出来的,如果有什么问题请朋友们指出了。

总结:上面只是涉及到了一些基本的数据操作,第一部分的数据操作还有什么添加索引啊,添加用户权限,用户权限认证什么的我还没贴出来,实际上我也还没完全弄清楚用户权限的这个,虽然有点复杂,但是我相信后面花点时间还是能够搞定的。至于第二部分,这不用做什么解释了,代码很清晰,一目了然滴。至于前面提到的Java的学习,我也没有中断过,已经学到了窗体中各种数据操作,后面会把Java学习心得发出来继续和大家分享,希望朋友们不要吝啬自己的知识,给我指点一下。关于MongoDB,如果只是学到这里,我认为还是不够的,比如如果去做读写分离,主库和从库的搭建和配置我都还没有去了解,还有一些安全的常识我也没有过多的了解,这些东西只有后面学习了再继续和大家分享我的心得咯,谢谢大家!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值