【大数据】MongoDB安装(转)

https://note.youdao.com/share/?id=40be7f77434910e8860c5fd1ef5d24fe&type=note#/

MongoDB安装

环境

CentOS 7

安装

官网下载mongodb-linux-x86_64-rhel70-3.4.9.tgz

将压缩包复制到/usr/local下面并解压

cd /usr/local
tar -xzvf mongodb-linux-x86_64-rhel70-3.4.9.tgz

进入MongoDB目录并建立存放数据的目录

cd mongodb-linux-x86_64-rhel70-3.4.9
mkdir -p data/db

启动MongoDB

bin/mongod --dbpath data/db

测试

使用mongo命令打开命令行

bin/mongo
> show dbs
> show collections
> show users
> use test
> db.help()
> db.user.help()
> db.user.save({userId:"zhangsan",name:"张三"})
> db.user.find()
> db.user.find().help()
> db.user.save({userId:"lisi",name:"王五"})
> db.user.update({userId:"lisi"}, {$set:{name:"李四"}}, false, true)
> db.user.remove({userId:"lisi"})
> db.user.find()

更多用法可以参考菜鸟教程

Java操作MongoDB

GitHub下载驱动mongo-java-driver-3.5.0.jar

private static void display(FindIterable<Document> result) {
    for (Document doc : result) {
        logger.debug(doc.toJson());
    }
}

private static void testMongoDB() throws Exception {
    MongoClient client = new MongoClient("192.168.1.181", 27017);
    MongoDatabase db = client.getDatabase("test");
    MongoCollection<Document> col = db.getCollection("users");
    Document user = new Document();
    user.append("userId", "zhangsan");
    user.append("name", "张三");
    user.append("sex", "男");
    col.insertOne(user);
    display(col.find());
    col.updateMany(Filters.eq("userId", "zhangsan"), new Document("$set", new Document("sex", "女")));
    display(col.find());
    col.deleteMany(Filters.eq("userId", "zhangsan"));
    display(col.find());
    client.close();
}
posted @ 2017-12-13 11:17  quietwalk  阅读(202)  评论(0编辑  收藏  举报