mongodb是分佈式數據庫,它與關係型數據庫有所不同。
mongoDB的一些安裝配置及注意:1,mongodb的數據是全部存儲在數據目錄data下面,但是在安裝時它不會自動創建這個文件目錄,所以我們要創建目錄data
方法如下:1.可以直接建裏文件夾data,並在其下建立data/db,以及data/log
2.可以在命令行中使用mkdir命令 如 mkdir data,會在對應的目錄下創建data下面
注意:一般data會放在跟目錄下面如:d:\data即可
還有一種方法暫時不明白
mongoDB一定注意是<Key:value>,[]:多個值時,{}:用於插入文檔,():
mongodb 後臺管理 shell
MonoDB shell命令操作語法和JavaScript很類似,其實控制檯底層的查詢語句都是用JavaScript腳本完成操作的。
Ø 數據庫
1、Help查看命令提示
help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help();
2、切換/創建數據庫
>use yourDB;
當創建一個集合(table)的時候會自動創建當前數據庫
3、查詢所有數據庫
show dbs;
4、刪除當前使用數據庫
db.dropDatabase();
5、從指定主機上克隆數據庫
db.cloneDatabase(“127.0.0.1”);
將指定機器上的數據庫的數據克隆到當前數據庫
6、從指定的機器上覆制指定數據庫數據到某個數據庫
db.copyDatabase("mydb", "temp", "127.0.0.1");
將本機的mydb的數據複製到temp數據庫中
7、修復當前數據庫
db.repairDatabase();
8、查看當前使用的數據庫
db.getName();
db;
db和getName方法是一樣的效果,都可以查詢當前使用的數據庫
9、顯示當前db狀態
db.stats();
10、當前db版本
db.version();
11、查看當前db的鏈接機器地址
db.getMongo();
Ø Collection聚集集合
1、創建一個聚集集合(table)
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
2、得到指定名稱的聚集集合(table)
db.getCollection("account");
3、得到當前db的所有聚集集合
db.getCollectionNames();
4、顯示當前db所有聚集索引的狀態
db.printCollectionStats();
Ø 用戶相關
1、添加一個用戶
db.addUser("name");
db.addUser("userName", "pwd123", true);
添加用戶、設置密碼、是否只讀
2、數據庫認證、安全模式
db.auth("userName", "123123");
3、顯示當前所有用戶
show users;
4、刪除用戶
db.removeUser("userName");
Ø 其他
1、查詢之前的錯誤信息
db.getPrevError();
2、清除錯誤記錄
db.resetError();
三、Collection聚集集合操作
Ø 查看聚集集合基本信息
1、查看幫助
db.yourColl.help();
2、查詢當前集合的數據條數
db.yourColl.count();
3、查看數據空間大小
db.userInfo.dataSize();
4、得到當前聚集集合所在的db
db.userInfo.getDB();
5、得到當前聚集的狀態
db.userInfo.stats();
6、得到聚集集合總大小
db.userInfo.totalSize();
7、聚集集合儲存空間大小
db.userInfo.storageSize();
8、Shard版本信息
db.userInfo.getShardVersion()
9、聚集集合重命名
db.userInfo.renameCollection("users");
將userInfo重命名爲users
10、刪除當前聚集集合
db.userInfo.drop();
Ø 聚集集合查詢
1、查詢所有記錄
db.userInfo.find();
相當於:select * from userInfo;
默認每頁顯示20條記錄,當顯示不下的情況下,可以用it迭代命令查詢下一頁數據。注意:鍵入it命令不能帶“;”
但是你可以設置每頁顯示數據的大小,用DBQuery.shellBatchSize = 50;這樣每頁就顯示50條記錄了。
2、查詢去掉後的當前聚集集合中的某列的重複數據
db.userInfo.distinct("name");
會過濾掉name中的相同數據
相當於:select distict name from userInfo;
3、查詢age = 22的記錄
db.userInfo.find({"age": 22});
相當於: select * from userInfo where age = 22;
4、查詢age > 22的記錄
db.userInfo.find({age: {$gt: 22}});
相當於:select * from userInfo where age > 22;
5、查詢age < 22的記錄
db.userInfo.find({age: {$lt: 22}});
相當於:select * from userInfo where age < 22;
6、查詢age >= 25的記錄
db.userInfo.find({age: {$gte: 25}});
相當於:select * from userInfo where age >= 25;
7、查詢age <= 25的記錄
db.userInfo.find({age: {$lte: 25}});
8、查詢age >= 23 並且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
9、查詢name中包含 mongo的數據
db.userInfo.find({name: /mongo/});
//相當於%%
select * from userInfo where name like ‘%mongo%’;
10、查詢name中以mongo開頭的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
11、查詢指定列name、age數據
db.userInfo.find({}, {name: 1, age: 1});
相當於:select name, age from userInfo;
當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列信息。
12、查詢指定列name、age數據, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相當於:select name, age from userInfo where age > 25;
13、按照年齡排序
升序:db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
14、查詢name = zhangsan, age = 22的數據
db.userInfo.find({name: 'zhangsan', age: 22});
相當於:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
15、查詢前5條數據
db.userInfo.find().limit(5);
相當於:select top 5 * from userInfo;
16、查詢10條以後的數據
db.userInfo.find().skip(10);
相當於:select * from userInfo where id not in (
select top 10 * from userInfo
);
17、查詢在5-10之間的數據
db.userInfo.find().limit(10).skip(5);
可用於分頁,limit是pageSize,skip是第幾頁*pageSize
18、or與 查詢
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相當於:select * from userInfo where age = 22 or age = 25;
19、查詢第一條數據
db.userInfo.findOne();
相當於:select top 1 * from userInfo;
db.userInfo.find().limit(1);
20、查詢某個結果集的記錄條數
db.userInfo.find({age: {$gte: 25}}).count();
相當於:select count(*) from userInfo where age >= 20;
21、按照某列進行排序
db.userInfo.find({sex: {$exists: true}}).count();
相當於:select count(sex) from userInfo;
Ø 索引
1、創建索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});
2、查詢當前聚集集合所有索引
db.userInfo.getIndexes();
3、查看總索引記錄大小
db.userInfo.totalIndexSize();
4、讀取當前集合的所有index信息
db.users.reIndex();
5、刪除指定索引
db.users.dropIndex("name_1");
6、刪除所有索引索引
db.users.dropIndexes();
Ø 修改、添加、刪除集合數據
1、添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
添加的數據的數據列,沒有固定,根據添加的數據爲準
2、修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相當於:update users set name = ‘changeName’ where age = 25;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相當於:update users set age = age + 50 where name = ‘Lisi’;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相當於:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;
3、刪除
db.users.remove({age: 132});
4、查詢修改刪除
db.users.findAndModify({
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
db.runCommand({ findandmodify : "users",
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
update 或 remove 其中一個是必須的參數; 其他參數可選。
參數 | 詳解 | 默認值 |
query | 查詢過濾條件 | {} |
sort | 如果多個文檔符合查詢過濾條件,將以該參數指定的排列方式選擇出排在首位的對象,該對象將被操作 | {} |
remove | 若爲true,被選中對象將在返回前被刪除 | N/A |
update | 一個 修改器對象 | N/A |
new | 若爲true,將返回修改後的對象而不是原始對象。在刪除操作中,該參數被忽略。 | false |
fields | 參見Retrieving a Subset of Fields (1.5.0+) | All fields |
upsert | 創建新對象若查詢結果爲空。 示例 (1.5.4+) | false |
Ø 語句塊操作
1、簡單Hello World
print("Hello World!");
這種寫法調用了print函數,和直接寫入"Hello World!"的效果是一樣的;
2、將一個對象轉換成json
tojson(new Object());
tojson(new Object('a'));
3、循環添加數據
> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };
這樣就循環添加了30條數據,同樣也可以省略括號的寫法
> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
也是可以的,當你用db.users.find()查詢的時候,顯示多條數據而無法一頁顯示的情況下,可以用it查看下一頁的信息;
4、find 遊標查詢
>var cursor = db.users.find();
> while (cursor.hasNext()) {
printjson(cursor.next());
}
這樣就查詢所有的users信息,同樣可以這樣寫
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }
同樣可以省略{}號
5、forEach迭代循環
db.users.find().forEach(printjson);
forEach中必須傳遞一個函數來處理每條迭代的數據信息
6、將find遊標當數組處理
var cursor = db.users.find();
cursor[4];
取得下標索引爲4的那條數據
既然可以當做數組處理,那麼就可以獲得它的長度:cursor.length();或者cursor.count();
那樣我們也可以用循環顯示數據
for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);
7、將find遊標轉換成數組
> var arr = db.users.find().toArray();
> printjson(arr[2]);
用toArray方法將其轉換爲數組
8、定製我們自己的查詢結果
只顯示age <= 28的並且只顯示age這列數據
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
9、forEach傳遞函數顯示信息
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
上面介紹過forEach需要傳遞一個函數,函數會接受一個參數,就是當前循環的對象,然後在函數體重處理傳入的參數
如果你需要進入MongoDB後臺管理,你需要先打開mongodb裝目錄的下的bin目錄,然後執行mongo.exe文件,MongoDB Shell是MongoDB自帶的交互式Javascript shell,用來對MongoDB進行操作和管理的交互式環境。
啓動mongodb服務器執行mongod.exe,連接mongod服務器執行mongo.exe.
對比記憶MySQL與mongoDB
SQL術語/概念 | MongoDB術語/概念 | 解釋/說明 |
---|---|---|
database | database | 數據庫 |
table | collection | 數據庫表/集合 |
row | document | 數據記錄行/文檔 |
column | field | 數據字段/域 |
index | index | 索引 |
table joins | 表連接,MongoDB不支持 | |
primary key | primary key | 主鍵,MongoDB自動將_id字段設置爲主鍵 |
命令
db:用於查看當前的文檔(數據庫)默認爲test.
use:用於創建一個數據庫,有則不建,沒有則新建。 如:use database.
show dbs:用於查看數據庫名.
db.dropDatabase():用於刪除當前數據庫.
db.collection.drop():用於刪除集合(表).
db.collection.insert({key:value,[key:value]...}):用於插入數據.
db.collection.find():用於查找信息 ,可以單行/多行插入.
db.collection.update(query,update):用於更新信息,可以單行/多行更新.
如:db.collection.update({'age':18},{$set:{'age':19}}),注意構成的符號
db.collection.remove(query,justone):用於刪除文檔(行).現已用db.inventory.deleteOne()代替 如:db.collection.remove({'age':18}),注意構成的符號
db.collection.find(query,projection):用於查找信息 ,參數均可選,query爲條件,projection爲投影。注意多個條件and 與or 的關係的寫法。
如db.collection.find({'name':'david','sex':'男'}),此句類似於
where(name = 'david' and sex="男")
db.collection.find($or:[{'name':'david','sex':'男'}]),此句類似於
where(name = 'david' or sex="男")
db.adminCommand({renameCollection: "db1.test1", to: "db2.test2"}) 用於更改數據庫的名字
條件操作符:gt(greater than),gte(gt equal),lt(less than),lte(lt equal),ne(not equal)
索引:db.collection.ensureIndex({'key':1}),索引是對數據庫表中一列或多列的值進行排序的一種結構。其中1——升序,-1——降序。
聚合:db.collection.aggregate([{$group:{_id:"$by_user",num_total:{$sum:1}}}])注意符號
類似於 select by_user as _id,count(*) as num_total group by by_user
java與mongoDB
首先一定注意在對mongoDB進行增刪改查操作時,首先保證mongoDB服務器開啓,然後在進行連接,否則可能會出現timeoutException
首先引入java與mongoDB,連接的jdbc.jar包。
//與mongoDB建立連接
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 連接到數據庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
// 獲取集合(表)
MongoCollection<Document> collection = mongoDatabase.getCollection("person");
// 獲取迭代器(因爲集合用Iteator 遍歷)
FindIterable<Document> findIterable = collection.find();
// 獲取指針
MongoCursor<Document> mongoCursor = findIterable.iterator();
以上這些步驟爲重要的,其他的可以查閱資聊料。
mongoDB的兩種引用:手動引用和DBrefs
當一個文檔引用多個集合裏的文檔時,就用DBrefs引用
基本知識不講,只需注意一點的是查詢
var document(記錄) = db.collection(集合).find();
var dbref = document.column(列);
db[dbref.$ref].findOne({_id:ObjectId(dbref.$id)}):表示從參考表中查找id的信息
紅色重點注意,符號不能變。
//--- by jxw mongo更新語句不存在及添加,存在則替換
Document filter = new Document("userDevSn",userDevSn);
// 若存在則替換,否則爲插入
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
options.upsert(true);
// 必須去掉,否則無法更新
document.remove("_id");
collectionLatest.findOneAndUpdate(filter, new Document("$set",document), options);
question
1. java語言對mongodb進行操作時,會用到MongoCusor這個類,而這個類有時會顯示線程不安全,線程不安全即:當一個線程訪問文檔時,其他線程等待,直到結束,才換另一個現成叫線程安全,而多個線程可以同時訪問文檔及線程不安全。當用該類的hasnext()時會出現false;有說法是說線程不安全,導致鏈接終斷,會出現連接時間過長,在控制檯上。
sollution:將MongonDatabase,MongoCollection類設置爲static:可能縮短鏈接時間吧;
2.從前臺向數據庫添加中文,以及從數據庫取出內容顯示,均爲亂碼,原因:
sollution:
3.從前臺提交數據或從後臺取出數據傳給前臺,出現中文亂碼,
sollution:可能是method方法有誤,或者就用filter對所有的request進行編碼過濾,或者單獨進行重新編碼如:document = db.find1(new String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8"));對name參數的值進行解析,重新用utf-8編碼即可。