zoukankan      html  css  js  c++  java
  • MongoDb 配置笔记

    安装:

    官网:https://www.mongodb.org/

    按官方教程: http://docs.mongodb.org/master/tutorial/install-mongodb-on-red-hat/

    设置

    linux 下修改数据文件地址:

    /etc/mongod.conf

    修改: dbpath,logpath

    一定要注意,指定的位置需要使用命令:

    sudo chmod o+rwx 新的MongoData路径

    在修改了: /etc/selinux/config 之后, 一定要重启才能生效。

    启动:

    /usr/bin/mongod -f /etc/mongod.conf

    开机启动:

    sudo chkconfig --level 3 mongod

    设置远程连接

    打开: /etc/mongodb.conf ,修改 bind_ip=对外IP,0.0.0.0 (不能是 127.0.0.1)

    不能注释, 如果注释的话, 用 netstat -anlp | grep 27017 查看, 它还绑定到 127.0.0.1 上!

    重启: sudo service mongod restart

    客户端连接:  mongo  ip:port

    开机启动:

    http://blog.csdn.net/u012979009/article/details/48052223

    查看 mongo 路径:

    $which mongod

      usr/bin/mongod

    $ touch etc/init.d/mongod  

    $ chmod 777 etc/init.d/mongod  

    $ vi etc/init.d/mongod  

    #!/bin/sh
    #
    #chkconfig: 2345 80 90
    #description: mongodb
    
    if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
       echo never > /sys/kernel/mm/transparent_hugepage/enabled
    fi
    if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
       echo never > /sys/kernel/mm/transparent_hugepage/defrag
    fi
    
    start() {
        usr/bin/mongod -f /etc/mongod.conf
    }
    
    stop() {
      usr/bin/mongod -f /etc/mongod.conf --shutdown
    }
    
    case "$1" in
      start)
        start
        ;;
      stop)
        stop
        ;;
      restart)
        stop
        start
        ;;
      *)
     echo $"Usage: $0 {start|stop|restart}"
     exit 1
    esac

    $ chkconfig --add mongod  

    $ chkconfig mongod on  

    $ service mongod start  

    无法启动Service

    Failed to start mongod.service: Unit mongod.service not found.

    mongod --config /etc/mongod.conf  --fork

    用户名密码

    1. 先注释 /etc/mongod.conf 里的:

    #security:
    # authorization: enabled

    2. 重启 mongod

    service mongod restart 在 Ubunu16.04 ,mongo3.6下不好使,执行完后,没有错误提示,但是没有效果.

    ps aux | grep mongo

    kill -9  pid

    /usr/bin/mongod -f /etc/mongod.conf &

    3.  清除用户

    use admin

    db.system.users.remove({})

    4. 添加用户:

    先添加 root 角色

    use admin

    db.createUser( { user: "admin" , pwd:"123", roles:[ "root" ,  "readWrite" ]   } );

    再创建数据库

    use pzx

    db.createUser( { user: "pzx" , pwd:"123", roles:[ "dbOwner" ,  "readWrite" ]   } );

    连接:

      mongo  数据库 --host ip  -u pzx -p 123 

      注意,启用用户名密码后, 必须填写 数据库 名字。

     连接字符串: 

    spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

     修改密码

    https://yq.aliyun.com/articles/43274

    db.changeUserPassword('tank2','test');    

    导出

    mongodump --host=ip  --port=27717  --username=pzx_online  --password=    --db=pzx_online  --out=./

    导入

    mongorestore --host=ip --port=27717 --username=pzx  --password=  --db=pzx  --dir=./pzx_online

    教程:

    1. 如何使用内存:http://www.oschina.net/question/16840_44521

    2. MongoDb连接字符串标准:http://www.cnblogs.com/hantianwei/archive/2012/10/15/2725049.html

    C#官方的驱动:https://github.com/mongodb/mongo-csharp-driver

    C#驱动教程: https://docs.mongodb.org/getting-started/csharp/

    Java官方的驱动:http://mongodb.github.io/mongo-java-driver/

    Java驱动教程: https://docs.mongodb.org/getting-started/java/

    驱动有四个版本,目前还不清楚它们的区别, mongo-java-driver 的在线教程:http://mongodb.github.io/mongo-java-driver/3.2/driver/getting-started/quick-tour/

    Mongo扩展的Json:如: $date , $oid

    https://docs.mongodb.com/v2.6/reference/mongodb-extended-json/

    Mongo配置文件官方

    https://docs.mongodb.com/manual/reference/configuration-options/

    客户端工具

    vue不能方便执行命令。推荐使用:

    Robomongo  选 Robo 3T  : https://robomongo.org/

    NoSql Manager :http://www.mongodbmanager.com/download

    更多工具: https://docs.mongodb.org/ecosystem/tools/administration-interfaces/

     

     防火墙

     禁用防火墙

    centos 7:
    systemctl stop firewalld.service #停止
    systemctl disable firewalld.service #禁用

    防火墙添加端口号

       firewall-cmd --zone=public --add-port=27017/tcp --permanent

       firewall-cmd --reload

    如果添加Http端口,则:

    firewall-cmd --permanent --zone=public --add-service=http 

     监控

    http://blog.csdn.net/yyywyr/article/details/26816809

    导出Json

    mongoexport -h 192.168.8.161 -u ptr -p 1234 -d ptr -c resume -o abc.json

    -h:数据库宿主机的IP

    -u:数据库用户名

    -p:数据库密码

    -d:数据库名字

    -c:集合的名字

    -f:导出的列名

    -q:导出数据的过滤条件

    --csv:导出格式为csv

    --quiet  安静模式,不显示进度 

    mongoimport -d local -c gis  --type json --file likehua.data  -f username,_id

    命令行

    参考:http://blog.csdn.net/shirdrn/article/details/7105539

    登录: mongo  -u ptr -p 1234 192.168.8.161/ptr

    数组

    role是user的数组属性

    更新数组中的行数据:

    db.sysUser.update({ "_id":ObjectId("58dcc7e0b69b336a71c724c6") } ,{ "$set": {"role.1.name":"--abc--"}  });

    按数组中的查询条件,进行更新

    db.sysUser.update({ "_id":ObjectId("58dcc7e0b69b336a71c724c6") ,"role._id":"12"} ,{ "$set": {"role.$.name":"--xxxx--"} });

    封装

    先定义一个配置节

        public class MongoConfigSect : ConfigurationSection
        {
            [ConfigurationProperty("Entitys")]
            public EntityCollection Entitys
            {
                get { return this["Entitys"] as EntityCollection; }
            }
    
            public class EntityCollection : ConfigurationElementCollection
            {
                public IEnumerable<GroupCollection.EntityElement> GetConfig(Func<GroupCollection.EntityElement, bool> func)
                {
                    foreach (GroupCollection group in this)
                    {
                        foreach (GroupCollection.EntityElement tab in group)
                        {
                            if (func(tab)) yield return tab;
                        }
                    }
                }
    
    
                public GroupCollection.EntityElement GetConfig(string Entity)
                {
                    foreach (GroupCollection group in this)
                    {
                        foreach (GroupCollection.EntityElement tab in group)
                        {
                            if (tab.Name == Entity ) return tab;
                        }
                    }
                    return new GroupCollection.EntityElement(new GroupCollection(this));
                }
    
                [ConfigurationProperty("db", IsRequired = false)]
                public string db
                {
                    get
                    {
                        var theDb = this["db"].AsString();
                        if (theDb.HasValue()) return theDb;
                        else return "dbo";
                    }
                }
    
                protected override ConfigurationElement CreateNewElement()
                {
                    return new GroupCollection(this);
                }
    
                protected override object GetElementKey(ConfigurationElement element)
                {
                    GroupCollection siteUser = element as GroupCollection;
                    return siteUser.Name;
                }
    
                public override ConfigurationElementCollectionType CollectionType
                {
                    get
                    {
                        return ConfigurationElementCollectionType.BasicMap;
                    }
                }
                protected override string ElementName
                {
                    get
                    {
                        return "Group";
                    }
                }
    
    
                public class GroupCollection : ConfigurationElementCollection
                {
                    public EntityCollection Container { get; private set; }
    
                    public GroupCollection(EntityCollection entityCollection)
                    {
                        this.Container = entityCollection;
                    }
    
                    [ConfigurationProperty("Name")]
                    public string Name
                    {
                        get { return (string)this["Name"]; }
                    }
    
                    [ConfigurationProperty("db", IsRequired = false)]
                    public string db
                    {
                        get
                        {
                            var theDb = this["db"].AsString();
                            if (theDb.HasValue()) return theDb;
                            else return Container.db;
                        }
                    }
    
    
                    protected override ConfigurationElement CreateNewElement()
                    {
                        return new EntityElement(this);
                    }
    
                    protected override object GetElementKey(ConfigurationElement element)
                    {
                        EntityElement siteUser = element as EntityElement;
                        return siteUser.Name;
                    }
    
                    public override ConfigurationElementCollectionType CollectionType
                    {
                        get
                        {
                            return ConfigurationElementCollectionType.BasicMap;
                        }
                    }
                    protected override string ElementName
                    {
                        get
                        {
                            return "Entity";
                        }
                    }
    
    
    
                    public class EntityElement : ConfigurationElement
                    {
                        public GroupCollection Container { get; private set; }
    
                        public EntityElement(GroupCollection groupCollection)
                        {
                            this.Container = groupCollection;
                        }
    
                        
                        [ConfigurationProperty("Name")]
                        public string Name
                        {
                            get { return this["Name"] as string; }
                        }
    
                         
                        [ConfigurationProperty("db", IsRequired = false)]
                        public string db
                        {
                            get
                            {
                                var theDb = this["db"].AsString();
                                if (theDb.HasValue())
                                {
                                    return theDb;
                                }
                                else return Container.db;
                            }
                        }
                    }
                }
            }
        }
    View Code

    再定义一个助手类

    public static partial class mor
    {
        //配置项
        private static MongoConfigSect Sect;
    
        private static Dictionary<string, IMongoDatabase> dbs = new Dictionary<string, IMongoDatabase>();
    
        static mor()
        {
            dbs = new Dictionary<string, IMongoDatabase>();
            var em = ConfigurationManager.ConnectionStrings.GetEnumerator();
            while (em.MoveNext())
            {
                var current = em.Current as ConnectionStringSettings;
                if (current.ProviderName.Is("mongo") == false) { continue; }
                dbs.Add(current.Name, GetMongoDb(current.ConnectionString));
            }
    
            Sect = (MongoConfigSect)ConfigurationManager.GetSection("Mongo");
        }
    
    
        private static string GetDbName(string ConnectionString)
        {
            //http://www.cnblogs.com/hantianwei/archive/2012/10/15/2725049.html
            //mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000
    
            var connStr = ConnectionString.Slice("mongodb://".Length);
            var m = Regex.Match(connStr, @"/w*", RegexOptions.Compiled);
            if (m.Success)
            {
                return m.Value.Slice(1);
            }
            return null;
        }
    
    
        private static IMongoDatabase GetMongoDb(string ConnectionString)
        {
            var mongoUrl = new MongoUrl(ConnectionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            if (!clientSettings.WriteConcern.IsAcknowledged)
            {
                clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says
            }
    
            clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(500);
    
            var client = new MongoClient(clientSettings);
    
            return client.GetDatabase(GetDbName(ConnectionString));
        }
    
        private static IMongoCollection<T> GetCollection<T>(string Name = null)
        {
    
            //var name = typeof(T).FullName.MySplit('.').Last();
            //var configName = Sect.Entitys.GetConfig(name).db;
    
            //return dbs[configName].GetCollection<T>(name);
            var name = !string.IsNullOrEmpty(Name) ? Name : typeof(T).FullName.MySplit('.').Last();
    
            var configName = Sect.Entitys.GetConfig(name).db;
    
            return dbs[configName].GetCollection<T>(name);
        }
    
        private static Dictionary<string, object> _dict = new Dictionary<string, object>();
    
    
        private static IMongoCollection<T> Get<T>(string name = null)
        {
            if (!string.IsNullOrEmpty(name))
            {
                if (_dict.ContainsKey(name) == false)
                {
                    _dict[name] = GetCollection<T>(name);
                }
                return _dict[name] as IMongoCollection<T>;
            }
            else
            {
                var typeName = typeof(T).FullName;
                if (_dict.ContainsKey(typeName) == false)
                {
                    _dict[typeName] = GetCollection<T>();
                }
                return _dict[typeName] as IMongoCollection<T>;
            }
    
    
        }
    
    }
    View Code

    再手动扩展:

    public static partial class mor
    {
        public static IMongoCollection<WebFileInfo> WebFileInfo { get { return Get<WebFileInfo>(); } }
    }

    就可以使用了:

    mor.WebFileInfo. 各种Mongo操作。

    Mongo的 Find方法是扩展方法,需要 using MongoDB.Driver; 

    如果频繁操作Mongo,需要把连接池设置到足够大,否则报错。

    clientSettings.MaxConnectionPoolSize = 10000;

    C#使用

    Bson是核心

    可以这样理解,Bson是Json的扩展格式,Bson比Json更容易定位,Bson,在存储的时候,多存储了Json.Value的长度,类型等信息。

    BsonDocument =》 Json

    BsonElement => Json中的一行。

    动态条件查询

    我更喜欢调用更底层一些的方法,而不是它封装好的Lambda。因为它的Lambda是基于 Expression的, 我在动态构造查询条件时,很费劲。

    动态条件查询: http://www.cnblogs.com/lori/p/4536595.html

    例子:

    var where = new BsonDocument();
    
    if (Mobile.HasValue())
    {
        where.Add(new BsonElement("Phone", BsonValue.Create(Mobile)));
    }
    
    if (IDCode.HasValue())
    {
        where.Add(new BsonElement("IdentityCode", BsonValue.Create(IDCode)));
    }
    
    if (Email.HasValue())
    {
        where.Add(new BsonElement("Email", BsonValue.Create(Email)));
    } 
                 
    var selectFields = Builders<mor.JobSeekerModel>.Projection.Include("_id");
    
    var Ids = mor.JobSeekerInfo
        .Find(new BsonDocumentFilterDefinition<mor.JobSeekerModel>(where))
        .Project(selectFields)
        .ToListInline()
        .Select(o => o.GetValue("_id").AsString)
        .ToArray()
        ;
    View Code

    JavaScript

    Mongo集成Javascript才是真正的逆天。

    where

    db.jianli.find( "this.JianLiContentTXT.length > 2000" ).limit(1)

    =

    db.jianli.find(function(){ return this.JianLiContentTXT.length > 2000 ;} ).limit(1)

    导出所有的索引

    var ary = [];
    db.getCollectionNames().forEach(function(it){
         
        var iks =  db.getCollection(it).getIndexes() ;
        
    
        iks = iks.filter( function(it) { return !("_id" in it.key)  } )
        
        if( iks.length < 1){
            return ;
        }
        
        iks.forEach(function(it){ delete it.v ; it.collection  =  it.ns.split(".").slice(-1)[0]  ; delete it.ns; } )
        
     
        Array.prototype.push.apply(ary,  iks )
    })
    
    
    printjson(ary);

    重建索引:

    var ary = [] ;// 上面生成的数据.
    ary.forEach(function(it){ db.getCollection(it.collection).dropIndex(it.key); db.getCollection(it.collection).ensureIndex(it.key,{"unique":it.unique || false , name : it.name }) });

    优化

    1. 使用 ObjectId 类型的 _id

    2. 遍历集合时,使用 _id 排序 比 无排序 更快。

    http://www.jb51.net/article/62654.htm

    后记

    1. 它不成熟,还有很多坑,不应该在系统中作为主要业务库使用。

    2. 性能的话,也仅高一个数量级而己。完全可以在关系型数据库上做索引,分表 等优化。

    3. 优先使用关系型数据库,如果关系型数据库解决不了,则可以针对性升级, 针对查询,使用 Es , 针对存储,使用 Redis。

    4. 它会持续影响数据的使用方式,设计时,运行时,数量暴发时,等等。达不到一劳永逸的效果。

  • 相关阅读:
    LeetCode 【1】 Two Sum --001
    计算机网络-自定向下方法之应用层
    Android TextView自动换行、排列错乱问题及解决
    Android ScrollView内部组件设置android:layout_height="fill_parent"无效的解决办法
    Gson解析空字符串异常的处理
    AndroBench手机性能测试
    使用adb命令通过IP地址连接手机
    Android string.xml 添加特殊字符
    Android string资源 包含 数学符号等特殊字符 及 参数占位符
    Android Studio多渠道打包(二)
  • 原文地址:https://www.cnblogs.com/newsea/p/4668842.html
Copyright © 2011-2022 走看看