mac下安裝MongoDb

MongoDb初體驗

背景:在看了網上N篇教程以後,發現了各類不靠譜,因而開始踏上踩坑Mongo之路。java

1. 安裝MongoDb3.6 和 Mongod

1.安裝
curl -O https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.2.tgzweb

2.解壓
/opt/soft/mongo/mongodb

3.環境變量
vi ~/.bash_profile數據庫

export MONGO_PATH=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2
export PATH=$PATH:$MONGO_PATH/bin

source ~/.bash_profile後端

4.添加Mongo數據庫db安全

mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/db
chmod -R 777 /opt/soft/mongo/

5.添加Mongo配置文件bash

mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/etc
cd etc && touch mongod.confapp

#mongodb config file
dbpath=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/db
logpath=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs/mongodb/mongod.log
logappend = true
bind_ip = 127.0.0.1
journal=true
port = 27017
# fork容許後端子進程啓動,終端能夠隨便關
fork = true
# 安全權限,能夠先以非受權模式啓動Mongod,添加完用戶db.addUser('root','pwd') ,再開啓auth = true 後,db.auth('root','pwd'),帶密碼登錄
auth = true

6.添加log文件curl

mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs/mongodb/
touch mongod.log

2. 起飛

1.啓動ui

mongod --config /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/etc/mongod.conf

2.訪問數據庫

mongo3.x 以後就沒有web控制檯了,不要網上搜了,各類帖子都是老掉牙的,建議下載一個mongo客戶端,做爲操做

https://download.studio3t.com/studio-3t/mac/5.7.3/Studio-3T.dmg

也能夠手動再開終端,使用 mongo 命令鏈接上來,show db 等命令手動增刪改查數據庫。

9.命令

* 1.終端鏈接 `mongo`
* 2.查看庫 `show dbs`
* 3.建立DB `use demoDb` 使用demoDb(無則建立)
* 4.建立表 `db.democollection.insert({name:"jackMa",age:18})` 自動建立表,並插入一條Json
* 5.查看錶 `show collections`
* 6.主鍵 Every document stored in MongoDB must have an "_id" key, and you can have other keys as many as your wish.Mongo會自動插入一列叫 "_id",能夠本身在程序裏處理這個字段,插入到Mongo中,達到聯合主鍵的目的,Mongo自己不支持聯合主鍵
* 7.查詢 `db.democollection.find({}).limit(1000);`
* 8.js查詢 
    ```
    let mongodb = require("mongodb");
    let client = mongodb.MongoClient;
    let url = "mongodb://host:port/msginfo";
    
    client.connect(url, function (err, db) {
    
    let collection = db.collection("msg_phone");
    
    let query = {};
    let limit = 1000;
    
    let cursor = collection.find(query).limit(limit);
    
    cursor.forEach(
        function(doc) {
            console.log(doc["_id"]);
        },
        function(err) {
            db.close();
        }
    ); 
    });
    ```

3.Demo

  1. Pom
    ```


    org.mongodb
    mongo-java-driver
    3.2.0

    ```
  2. Test

    MongoDb.java

    package com.demo.util;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.mongodb.MongoClient;
    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.result.UpdateResult;
    import org.bson.Document;
    import org.bson.conversions.Bson;
    
    /**
     * @author luoyu.lzy
     * @Title: MongoDb.java
     * @Package com.demo.util
     * @Description:
     * @date 2018/1/17.
     */
    public class MongoDb {
    
        private static MongoCollection<Document> collection;
    
        /**
         * 連接數據庫
         *
         * @param databaseName
         *            數據庫名稱
         * @param collectionName
         *            集合名稱
         * @param hostName
         *            主機名
         * @param port
         *            端口號
         */
        public static void connect(String databaseName, String collectionName,
            String hostName, int port) {
            @SuppressWarnings("resource")
            MongoClient client = new MongoClient(hostName, port);
            MongoDatabase db = client.getDatabase(databaseName);
            collection = db.getCollection(collectionName);
            System.out.println(collection);
        }
    
        /**
         * 插入一個文檔
         *
         * @param document
         *            文檔
         */
        public static void insert(Document document) {
            collection.insertOne(document);
        }
    
        /**
         * 查詢全部文檔
         *
         * @return 全部文檔集合
         */
        public static List<Document> findAll() {
            List<Document> results = new ArrayList<Document>();
            FindIterable<Document> iterables = collection.find();
            MongoCursor<Document> cursor = iterables.iterator();
            while (cursor.hasNext()) {
                results.add(cursor.next());
            }
    
            return results;
        }
    
        /**
         * 根據條件查詢
         *
         * @param filter
         *            查詢條件 //注意Bson的幾個實現類,BasicDBObject, BsonDocument,
         *            BsonDocumentWrapper, CommandResult, Document, RawBsonDocument
         * @return 返回集合列表
         */
        public static List<Document> findBy(Bson filter) {
            List<Document> results = new ArrayList<Document>();
            FindIterable<Document> iterables = collection.find(filter);
            MongoCursor<Document> cursor = iterables.iterator();
            while (cursor.hasNext()) {
                results.add(cursor.next());
            }
    
            return results;
        }
    
        /**
         * 更新查詢到的第一個
         *
         * @param filter
         *            查詢條件
         * @param update
         *            更新文檔
         * @return 更新結果
         */
        public static UpdateResult updateOne(Bson filter, Bson update) {
            UpdateResult result = collection.updateOne(filter, update);
    
            return result;
        }
    
        /**
         * 更新查詢到的全部的文檔
         *
         * @param filter
         *            查詢條件
         * @param update
         *            更新文檔
         * @return 更新結果
         */
        public static UpdateResult updateMany(Bson filter, Bson update) {
            UpdateResult result = collection.updateMany(filter, update);
    
            return result;
        }
    
        /**
         * 更新一個文檔, 結果是replacement是新文檔,老文檔徹底被替換
         *
         * @param filter
         *            查詢條件
         * @param replacement
         *            跟新文檔
         */
        public static void replace(Bson filter, Document replacement) {
            collection.replaceOne(filter, replacement);
        }
    
        /**
         * 根據條件刪除一個文檔
         *
         * @param filter
         *            查詢條件
         */
        public static void deleteOne(Bson filter) {
            collection.deleteOne(filter);
        }
    
        /**
         * 根據條件刪除多個文檔
         *
         * @param filter
         *            查詢條件
         */
        public static void deleteMany(Bson filter) {
            collection.deleteMany(filter);
        }
    }

    MongoTest.java

    package com.demo.util;
    
    import java.util.List;
    
    import com.mongodb.client.result.UpdateResult;
    import org.bson.Document;
    import org.junit.Before;
    import org.junit.Test;
    
    /**
     * @author luoyu.lzy
     * @Title: MongoTest.java
     * @Package com.demo.util
     * @Description:
     * @date 2018/1/17.
     */
    public class MongoTest {
        @Before
        public void before() {
            MongoDb.connect("dbName", "collectionName", "127.0.0.1", 27017);
        }
    
        @Test
        public void testInsert() {
            Document document = new Document();
            document.append("name", "wang").append("gender", "female");
            MongoDb.insert(document);
        }
    
        @Test
        public void testFindAll() {
            List<Document> results = MongoDb.findAll();
            for (Document doc : results) {
                System.out.println(doc.toJson());
            }
        }
    
        @Test
        public void testFindBy() {
            Document filter = new Document();
            filter.append("name", "li si");
            List<Document> results = MongoDb.findBy(filter);
            for (Document doc : results) {
                System.out.println(doc.toJson());
            }
        }
    
        @Test
        public void testUpdateOne() {
            Document filter = new Document();
            filter.append("gender", "male");
    
            //注意update文檔裏要包含"$set"字段
            Document update = new Document();
            update.append("$set", new Document("gender", "female"));
            UpdateResult result = MongoDb.updateOne(filter, update);
            System.out.println("matched count = " + result.getMatchedCount());
        }
    
        @Test
        public void testUpdateMany() {
            Document filter = new Document();
            filter.append("gender", "female");
    
            //注意update文檔裏要包含"$set"字段
            Document update = new Document();
            update.append("$set", new Document("gender", "male"));
            UpdateResult result = MongoDb.updateMany(filter, update);
            System.out.println("matched count = " + result.getMatchedCount());
        }
    
        @Test
        public void testReplace() {
            Document filter = new Document();
            filter.append("name", "zhang");
    
            //注意:更新文檔時,不須要使用"$set"
            Document replacement = new Document();
            replacement.append("value", 123);
            MongoDb.replace(filter, replacement);
        }
    
        @Test
        public void testDeleteOne() {
            Document filter = new Document();
            filter.append("name", "li");
            MongoDb.deleteOne(filter);
        }
    
        @Test
        public void testDeleteMany() {
            Document filter = new Document();
            filter.append("gender", "male");
            MongoDb.deleteMany(filter);
        }
    }
相關文章
相關標籤/搜索