1. 程式人生 > >重新學習mongodb:操作mongodb資料庫

重新學習mongodb:操作mongodb資料庫

1.啟動shell

2.資料庫、集合、文件

3.插入和查詢

插入:db.users.insert({username:"smith"})

查詢:db.users.find()

mongodb的_id欄位:

傳遞查詢條件:db.users.find({username:"smith"});

db.users.find({$and:[{_id:ObjectId("5bc6c836efe8a9eb8c20aba4")},{username:"smith"}]})

db.users.find({$or:[{_id:ObjectId("5bc6c836efe8a9eb8c20aba4")},{username:"smith"}]})

4.更新文件

更新操作符:db.users.update({username:"smith"},{$set:{country:"Canada"}})

db.users.update({country:"Canada"},{$set:{usrname:"smith"}})

替換更新:db.users.update({usrname:"smith"},{username:"smith"})

db.users.update({username:"smith"},{$unset:{country:1}})

更新複雜的資料:

db.users.update(
    {username:"smith"},
    {
        $set:{
            favorites:{
                cities:["Chicago","Cheyenne"],
                movies:["Casablanca","For a few Dollara More","The String"]
            }
        }
})

db.users.update(
    {username:"jones"},
    {
        $set:{
            favorites:{
                movies:["Casablanca","Rocky"]
            }
        }
})

db.users.find({"favorites.movies":"Casablanca"})

高階更新:

5.刪除資料

清空資料:db.foo.remove()

按條件刪除:db.foo.remove({"favoritest.citys":"Cheyenne"})

刪除集合附帶刪除索引:db.foo.drop()

6.shell的其他特性:

db.help()

mongo --help

7.使用索引建立和查詢

for(i=0;i<20000;i++){

db.numbers.save({num:i});

}

7.1範圍查詢:$gt 和 $lt

db.numbers.find({"$and":[{num:{"$gt":1000}},{num:{"$lt":2000}}]})

7.2索引和explain()

分析:db.numbers.find({num:{"$gt":19995}}).explain("executionStats")

建立索引:db.numbers.createIndex({num:1})

8:基本管理

8.1:獲取資料庫的資訊 show dbs

     展示所有的集合:show  collections

    低級別資料庫和集合的分析:db.stats() ,db.numbers.stats()

8.2:命令如何執行:

db.runCommand({dastats:1})