MongoDB 常用shell命令匯總


//指定用戶名和密碼連接到指定的MongoDB數據庫

mongo 192.168.1.200:27017/admin -u user -p password

use youDbName

 

1.MongoDB 查詢所有索引的命令:

 

2.MongoDB 創建索引的命令:

Unique Index:

注:

  MongoDB無法創建指定的索引字段唯一索引(S)如果集合已經包含了將違反唯一性約束的數據指標。

  MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.

       https://docs.mongodb.com/v3.0/tutorial/create-a-unique-index/

解決方法:

  1.把集合數據導出(mongoexport)至csv文件備份。

  2.清空集合數據。

  3.創建 Unique Index

  4.將 步驟1 備份的csv文件導入(mongoimport)集合。會自動過濾掉重復的數據。

效果:

  

 

3.MongoDB 模糊匹配查詢:

 

4.MongoDB 查詢結果按指定字段排序:

 

5.MongoDB update功能:

  1.新增字段

  

  2.更新字段值($set

   

  db.StrategyInfo.update({},{$set:{“test”:”股票池”}},false,true);

  其中update()3個參數,表示不存在的記錄,是否插入,默認false,不插入。第4個參數,默認false只更新找到的第一條記錄;true表示全部更新。

 

  3.刪除某一列($unset

    

  

  4.重命名列名($rename

  

 

 6.更改某一列的字段類型

  1.查詢某一列的字段類型($type)

  

  

  2.更改(forEach)

  

  db.calcgsdataflash_once.find().forEach(function(x){x.f2=String(x.f2);db.calcgsdataflash_once.save(x)})

  

 

  

 

7.修改用戶密碼:

  db.changeUserPassword("root","123456")

  

8.修改某一列的值為另一列的值

db.student.find().forEach(
 function(item){
   db.student.update({"id":item._id},{"$set":{"newColumn":item.oldColumn}},true)
 }
)

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM