顯示具有 MongoDB 標籤的文章。 顯示所有文章
顯示具有 MongoDB 標籤的文章。 顯示所有文章

2020年11月6日 星期五

MongoDB 07.createIndex

無論是關聯式資料庫或是NoSQL
Index都相當重要
尤其在資料量大時特別顯著
MongoDB如何建立Index
目前使用Robo 3T來連線,右鍵資料庫 > Open Shell
語法如下
降冪-1升冪 1
1.單一欄位
db.collectionName.createIndex({"age":1})
2.多重欄位
db.collectionName.createIndex({"name":-1,"age":1})
也可以使用Robo 3T > Collection上右鍵 > Add Index
經過測試百萬筆資料後有Index跟無Index速度真的差很多
參考來源
db.collection.createIndex()
MongoDB 索引

MongoDB 06.C# Filter

查詢時基本上都會需要過濾條件
目前大概會使用到的如下
var builders = Builders.Filter;//建立查詢 
var filter = builders.Eq("age", 20);//過濾條件
var query = collection.Find(filter).ToList();//抓資料
條件如下
Eq等於
Ne不等於
Gt大於
Gte大於等於
Lt小於
Lte小於等於
Regex Like
In 存在裡面的
Nin 不存在裡面的
但通常條件不會這麼簡單
情境1.找年齡20~30歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
情境2.找年齡20~30歲或年齡50~60歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
情境3.找年齡20~30歲或年齡50~60歲且名字有林的
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
filter = filter & builders.Regex("Name", "林");
情境4.找年齡50、60、70歲
int[] agelist = new[] { 50, 60, 70 };
var filter = builders.In(x => x.age, agelist);
參考來源
Mongo C# driver - Building filter dynamically with nesting MongoDB C# Driver - Fastest way to perform an “IN” query on _id

2020年10月30日 星期五

MongoDB 05.備份與還原

1.前言
在網路上找就會有許多備份及還原的文章
mongodump
mongorestore
mongoexport
mongoimport
在命令提示字元中照貼語法都出現在列錯誤
'mongodump' 不是內部或外部命令、可執行的程式或批次檔。
後來檢查才發現根本沒這些執行檔阿
瀏覽官方文件,內容如下才發現原來我安裝的是目前最新的4.4版的,然後工具從4.4版後不包含在原本的裡面了
Starting with MongoDB 4.4, mongodump is now released separately from the MongoDB Server and uses its own versioning, with an initial version of 100.0.0. Previously, mongodump was released alongside the MongoDB Server and used matching versioning.
至官網下載MongoDB Database Tools
2.備份
-h: MongoDB連線IP或資訊
-port: Port
-d: 資料庫名稱
-o: 備份路徑資料夾
-u: 登入帳號
-p: 登入密碼
mongodump -h {host} -port {port} -d {yourdbname} -o {outputfloder} -u {username}-p {password}
mongodump -h localhost -port 27017 -d Happen -o d:\mongodb\bak -u Happen -p 7533967
完成後會在d:\mongodb\bak\Happen裡找到備份
3.還原
-d: 資料庫名稱
-u: 登入帳號
-p: 登入密碼
--drop: 以存在資料庫刪除原有的(注意)
mongorestore -d {yourdbname} --drop -o {outputfloder} -u {username}-p {password}
mongorestore -d Happen --droup  d:/mongodb/bak/happen -u Happen -p 7533967
參考來源
mongodump
[技術研究] 如何從遠端匯出MongoDB
5.備份及還原MongoDB(mongodump , mongorestore)

2020年10月29日 星期四

MongoDB 04.建立登入驗證

1.停用MongoDB Server服務
2.建立登入帳密
開啟命令提示字元,至安裝Mongodb目錄下輸入
mongo
>use yourdbname
>switched to db yourdbname
>db.createUser(
{
    user: "username",
    pwd: "password",
    roles: [ { role: "readWrite", db: "yourdbname" } ]
})
>Successfully added....
>db.auth('username','password')
1完成代表可以登入
0登入失敗
登入成功表示帳密無誤
3.設定mongod.cfg 找到
#security: 
改成
security:
    authorization: enabled


4.啟用MongoDB Server服務,寫程式即可使用上面的帳密登入,記得readWrite權限要開才能讀寫資料庫
5.Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1
檢查一下連線字串是否正確,或是權限是否正確
mongodb://username:password@localhost:27017/dbname
PS也可直接使用工具建立帳密
參考來源
為 MongoDB 加上驗證機制
mongodb設定使用者名稱和密碼並用node連線
Built-In Roles Configuring MongoDB authentication

MongoDB 03.使用.Net Core CRUD

1.如何在.Net Core上安裝MongoDB,完全不用擔心直接有套件可以支援MongoDB真是太佛心下列安裝方法均可
a.MongoDB官網
b.Nuget
2.如何使用
a.建立Model
    public class StaffInfo
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
       
        public string Name { get; set; }

        public int age { get; set; }

         
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime birthday { get; set; }

        public string remark { get; set; }

        public int likenumber { get; set; }
    }
b.宣告Interface
    public interface IStaffInfoService
    {     
        List Get();

        void Insert( StaffInfo model);     

        void Update( StaffInfo  model);

        void Delete(StaffInfo model);
    }
c.建立Service寫CURD
    public class StaffInfoService : IStaffInfoService
    {
        private readonly IMongoCollection _staffinfo;

        public StaffInfoService()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            //var client = new MongoClient("mongodb://{username}:{password}@{host}:{port}/{Database}")
            var database = client.GetDatabase("dbname");

            _staffinfo = database.GetCollection("tablename");
        }

        public void Delete(StaffInfo model)
        {
            _staffinfo.DeleteOne(x => x.Id == model.Id);
        }

        public List Get()
        {
            return _staffinfo.Find(StaffInfo => true).ToList();
        }

        public void Insert(StaffInfo model)
        {
            _staffinfo.InsertOne(model);
        }

        public void Update(StaffInfo model)
        {
            _staffinfo.ReplaceOne(x => x.Id == model.Id, model);
        }
    }
d.DI注入即可使用
參考來源
使用 ASP.NET Core 與 MongoDB 建立 Web API

2020年10月28日 星期三

MongoDB 02.開啟對外連線

剛安裝完成MongoDB後使用Robo3T連本機是沒問題的
但如果遠端要連的話會跳出錯誤
在安裝目錄下mongod.cfg 原本
# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1
修改為以下為不限制
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
修改為以下為開放本機及192.168.1.100
# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1 ,192.168.1.100
以上步驟修改完成後記得至服務重起MongoDB Server才會有效
參考來源
MongoDB 安裝完成後,開啟對外連線

MongoDB 01.安裝

一、MongoDB安裝
1.至官網下載
2.安裝點選剛剛的MSI檔基本上下一步到底,data log資料夾可依需求選擇,Install MongoDB Compass不要勾(參考網站內有指出勾選會卡住)
3.windows服務看MongoDB Server(MongoDB)有沒有執行中 4.開啟命令提示字元至剛剛安裝的路徑例如我是
cd C:\Program Files\MongoDB\Server\4.4\bin
輸入以下
mongod --version
有出現就安裝成功
db version v4.4.1
Build Info: {
    "version": "4.4.1",
    "gitVersion": "xxxx",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "windows",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}
5.4.4.1需Windows 10 or server 2016 所以如果下以下的可以使用4.2.10版
6.4.0.20版後安裝時可指定data跟log位置,之前版本可能要網路上找下指令方式
二、連線工具
1.Robomongo - Robo3T
2.下載Simple GUI for beginners 有免安裝的Download portable version for Windows 64-bit解壓後執行robo3t.exe即可使用
3.執行robo3t.exe > File > Connect > Create > Test 看是否建立成功
參考來源
Day17 - MongoDB 安裝設定
MongoDB - 詳細到讓人牙起來的安裝教學
Windows MongoDB 下載與安裝教學
MongoDB 使用Robo 3T建立資料庫