zoukankan      html  css  js  c++  java
  • 大数据课堂

    MongDB在安装过程中出现的一个问题(Unit mongod.service not found)(Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed

    在按照林子雨老师网站安装过程中
    自己一不小心把MongoDB的步骤弄错了 然后从头安装一遍 
    
    sudo service mongod start
    报错:
    Unit mongod.service not found.
    
    mongo
    报错:
    MongoDB shell version: 3.2.19
    connecting to: test
    2018-04-18T10:45:08.995+0800 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: errno:111 Connection refused
    2018-04-18T10:45:08.996+0800 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
    connect@src/mongo/shell/mongo.js:229:14
    @(conne5ct):1:6

    错误的原因是安装上了Mongo 的shell  没有安装上  Mongo   的 Service   解决办法 :重安装

    sudo apt-get install mongodb
     
    sudo  apt install mongodb-server

    MongoDB使用

    sudo service mongodb start
    
    pgrep mongo -l
    978 mongod
    
    mongo
    MongoDB shell version: 2.6.10
    connecting to: test
    
    show dbs
    School  0.078GB
    admin   (empty)
    local   0.078GB
    
    use School
    switched to db School
    
    show collections
    system.indexes
    > db.createCollection('teacher')
    { "ok" : 1 }
    
    > db.createCollection('student')
    { "ok" : 1 }
    
    > db.student.insert({_id:1, sname: 'zhangsan', sage: 20})
    WriteResult({ "nInserted" : 1 })
    
    > db.student.save({_id:1, sname: 'zhangsan', sage: 22})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.student.find()
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    > s= [{sname:'lisi',sage:20},{sname:'wangwu',sage:20},{sname:'chenliu',sage:22}]
    
    [
        {
            "sname" : "lisi",
            "sage" : 20
        },
        {
            "sname" : "wangwu",
            "sage" : 20
        },
        {
            "sname" : "chenliu",
            "sage" : 22
        }
    ]
    > db.student.insert(s)
    BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
    })
    > db.student.find()
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74597"), "sname" : "lisi", "sage" : 20 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74598"), "sname" : "wangwu", "sage" : 20 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74599"), "sname" : "chenliu", "sage" : 22 }
    > db.student.find().pretty()
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    {
        "_id" : ObjectId("5adeeaad949cd9c3aaf74597"),
        "sname" : "lisi",
        "sage" : 20
    }
    {
        "_id" : ObjectId("5adeeaad949cd9c3aaf74598"),
        "sname" : "wangwu",
        "sage" : 20
    }
    {
        "_id" : ObjectId("5adeeaad949cd9c3aaf74599"),
        "sname" : "chenliu",
        "sage" : 22
    }
    查找数据
    db.youCollection.find(criteria, filterDisplay)
    
    > db.student.find({sname: 'lisi'})
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74597"), "sname" : "lisi", "sage" : 20 }
    
    > db.student.find({},{sname:1, sage:1})
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74597"), "sname" : "lisi", "sage" : 20 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74598"), "sname" : "wangwu", "sage" : 20 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74599"), "sname" : "chenliu", "sage" : 22 }
    
    > db.student.find({sname: 'zhangsan', sage: 22})
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    
    > db.student.find({$or: [{sage: 22}, {sage: 25}]})
    { "_id" : 1, "sname" : "zhangsan", "sage" : 22 }
    { "_id" : ObjectId("5adeeaad949cd9c3aaf74599"), "sname" : "chenliu", "sage" : 22 }
    > db.student.update({sname: 'lisi'}, {$set: {sage: 30}}, false, true)
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.student.remove({sname: 'chenliu'})
    WriteResult({ "nRemoved" : 1 })
    
    db.student.drop()
    
    输入exit或者Ctrl+C退出shell命令模式

    MongoDB(JavaAPI)

    第一步:下载Java MongoDB Driver驱动jar包,Java MongoDB Driver下载地址,默认的下载目录~/下载或者~/Downloads
    第二步:打开Eclipse,新建Java Project,新建Class,引入刚刚下载的jar包
    第三步:编码实现
    下面以School数据库为例,执行集合student的增删改查操作,如果没有School数据库和student集合请先创建,以下是源代码:
        import java.util.ArrayList;
        import java.util.List;
         
        import org.bson.Document;
        import com.mongodb.MongoClient;
        import com.mongodb.client.MongoCollection;
        import com.mongodb.client.MongoCursor;
        import com.mongodb.client.MongoDatabase;
        import com.mongodb.client.model.Filters;
         
        public class TestMongoDB {
         
            /**
             * @param args
             */
            public static void main(String[] args) {
        //      insert();//插入数据。执行插入时,可将其他三句函数调用语句注释,下同
                find(); //查找数据
        //      update();//更新数据
        //      delete();//删除数据
            }
            /**
             * 返回指定数据库中的指定集合
             * @param dbname 数据库名
             * @param collectionname 集合名
             * @return
             */
            //MongoDB无需预定义数据库和集合,在使用的时候会自动创建
            public static MongoCollection<Document> getCollection(String dbname,String collectionname){
                //实例化一个mongo客户端,服务器地址:localhost(本地),端口号:27017
                MongoClient  mongoClient=new MongoClient("localhost",27017);
                //实例化一个mongo数据库
                MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
                //获取数据库中某个集合
                MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname);
                return collection;
            }
            /**
             * 插入数据
             */
            public static void insert(){
                try{
                    //连接MongoDB,指定连接数据库名,指定连接表名。
                    MongoCollection<Document> collection= getCollection("School","student");    //数据库名:School 集合名:student
                    //实例化一个文档,文档内容为{sname:'Mary',sage:25},如果还有其他字段,可以继续追加append
                    Document doc1=new Document("sname","Mary").append("sage", 25);
                    //实例化一个文档,文档内容为{sname:'Bob',sage:20}
                    Document doc2=new Document("sname","Bob").append("sage", 20);
                    List<Document> documents = new ArrayList<Document>(); 
                    //将doc1、doc2加入到documents列表中
                    documents.add(doc1); 
                    documents.add(doc2); 
                    //将documents插入集合
                    collection.insertMany(documents);  
                    System.out.println("插入成功"); 
                }catch(Exception e){
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                }
            }
            /**
             * 查询数据
             */
            public static void find(){
                try{
                    MongoCollection<Document> collection = getCollection("School","student");  //数据库名:School 集合名:student
                    //通过游标遍历检索出的文档集合 
        //          MongoCursor<Document>  cursor= collection.find(new Document("sname","Mary")). projection(new Document("sname",1).append("sage",1).append("_id", 0)).iterator();   //find查询条件:sname='Mary'。projection筛选:显示sname和sage,不显示_id(_id默认会显示)
                    //查询所有数据
                    MongoCursor<Document>  cursor= collection.find().iterator();
                    while(cursor.hasNext()){
                        System.out.println(cursor.next().toJson());
                    }
                }catch(Exception e){
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                }
            }
            /**
             * 更新数据
             */
            public static void update(){
                try{
                    MongoCollection<Document> collection = getCollection("School","student");  //数据库名:School 集合名:student
                     //更新文档   将文档中sname='Mary'的文档修改为sage=22   
                     collection.updateMany(Filters.eq("sname", "Mary"), new Document("$set",new Document("sage",22)));  
                     System.out.println("更新成功!");
                }catch(Exception e){
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                }
            }
            /**
             * 删除数据
             */
            public static void delete(){
                try{
                    MongoCollection<Document> collection = getCollection("School","student");  //数据库名:School 集合名:student
                        //删除符合条件的第一个文档  
                    collection.deleteOne(Filters.eq("sname", "Bob"));  
                    //删除所有符合条件的文档  
                    //collection.deleteMany (Filters.eq("sname", "Bob"));
                    System.out.println("删除成功!");
                }catch(Exception e){
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                }
            }
        }

     课后作业

    hadoop@hadoop-GL502VML:~$ mongo
    MongoDB shell version: 2.6.10
    connecting to: test
    > use Project
    switched to db Project
    > db.createCollection('menber')
    { "ok" : 1 }
    
    > n=[{name:'朱家丰',Title:'MINSt手写数字识别',Details:{assignment:'数据处理',weight:4,score:8}},{name:'蒋纪瑶',Title:'MINST手写数字识别',Details:{assignment:'数据收集',weight:3,score:8}},{name:'徐志伟',Title:'MINSt手写数字识别',Details:{assignment:'算法构建',weight:3,score:8}}]
    [
        {
            "name" : "朱家丰",
            "Title" : "MINSt手写数字识别",
            "Details" : {
                "assignment" : "数据处理",
                "weight" : 4,
                "score" : 8
            }
        },
        {
            "name" : "蒋纪瑶",
            "Title" : "MINST手写数字识别",
            "Details" : {
                "assignment" : "数据收集",
                "weight" : 3,
                "score" : 8
            }
        },
        {
            "name" : "徐志伟",
            "Title" : "MINSt手写数字识别",
            "Details" : {
                "assignment" : "算法构建",
                "weight" : 3,
                "score" : 8
            }
        }
    ]
    > db.menber.insert(n)
    BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
    })
    > db.menber.find().pretty()
    {
        "_id" : ObjectId("5adf1c004aee463a389fc303"),
        "name" : "朱家丰",
        "Title" : "MINSt手写数字识别",
        "Details" : {
            "assignment" : "数据处理",
            "weight" : 4,
            "score" : 8
        }
    }
    {
        "_id" : ObjectId("5adf1c004aee463a389fc304"),
        "name" : "蒋纪瑶",
        "Title" : "MINST手写数字识别",
        "Details" : {
            "assignment" : "数据收集",
            "weight" : 3,
            "score" : 8
        }
    }
    {
        "_id" : ObjectId("5adf1c004aee463a389fc305"),
        "name" : "徐志伟",
        "Title" : "MINSt手写数字识别",
        "Details" : {
            "assignment" : "算法构建",
            "weight" : 3,
            "score" : 8
        }
    }
    127.0.0.1       localhost
    127.0.1.1       hadoop-GL502VML
    192.168.145.219   Master
    192.168.145.140   Slave2
    172.19.77.75    Slave3
    # The following lines are desirable for IPv6 capable hosts
    ::1     ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
  • 相关阅读:
    WPF
    WPF RadioButton 转换
    JS框架之收集专帖
    WPF用ShowDialog()弹出窗体时控制该窗体的显示位置,并传值回父窗体
    WPF学习笔记:MVVM模式下,ViewModel如何关闭View?
    Microsoft Visual Studio 下载转帖
    RelayCommand命令
    动态调用webservice,不需要添加Web References
    你会在C#的类库中添加web service引用吗?
    Quartz Cron 触发器 Cron Expression 的格式
  • 原文地址:https://www.cnblogs.com/IAMzhuxiaofeng/p/8931462.html
Copyright © 2011-2022 走看看