成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

【mongoDB基礎(chǔ)篇①】安裝與常用操作語句

UCloud / 1103人閱讀

摘要:簡述與同為數(shù)據(jù)庫但是為數(shù)據(jù)庫而為文檔型數(shù)據(jù)庫存儲(chǔ)的是文檔的二進(jìn)制化內(nèi)部執(zhí)行引擎為解釋器把文檔存儲(chǔ)成結(jié)構(gòu)在查詢時(shí)轉(zhuǎn)換為對(duì)象并可以通過熟悉的語法來操作的安裝啟動(dòng)在上直接下載解壓運(yùn)行即可本身是已編譯好的二進(jìn)制可執(zhí)行文件如果報(bào)錯(cuò)說明你的服務(wù)器和

簡述

mongoDB與redis同為noSql數(shù)據(jù)庫,但是redis為kv數(shù)據(jù)庫(key/value),而mongoDB為文檔型數(shù)據(jù)庫存儲(chǔ)的是文檔(Bson->json的二進(jìn)制化).內(nèi)部執(zhí)行引擎為JS解釋器, 把文檔存儲(chǔ)成bson結(jié)構(gòu),在查詢時(shí),轉(zhuǎn)換為JS對(duì)象,并可以通過熟悉的js語法來操作

mongoDB的安裝啟動(dòng)

在linux上直接下載解壓運(yùn)行即可,本身是已編譯好的二進(jìn)制可執(zhí)行文件.
如果報(bào)錯(cuò)
-bash: /usr/local/mongodb/bin/mongod: cannot execute binary file
說明你的服務(wù)器和mongodb 的版本不對(duì)應(yīng), 如果服務(wù)器是64位,下載x86_64的mongodb ,如果服務(wù)器是32位的, 下載i686的mongodb/

BIN目錄說明
bsondump 導(dǎo)出BSON結(jié)構(gòu)
mongo 客戶端
mongod 服務(wù)端
mongodump 整體數(shù)據(jù)庫二進(jìn)制導(dǎo)出
mongoexport 導(dǎo)出易識(shí)別的json文檔或csv文檔
mongorestore 數(shù)據(jù)庫整體導(dǎo)入
mongos 路由器(分片用)
mongofiles GridFS工具,內(nèi)建的分布式文件系統(tǒng)
mongoimport 數(shù)據(jù)導(dǎo)入程序
mongotop 運(yùn)維監(jiān)控
mongooplog 
mongoperf
mongostat
啟動(dòng)
#啟動(dòng)服務(wù)端
./mongod --dbpath /usr/local/mongodb/data --logpath /usr/local/mongodb/logs/mongo.log --fork --port 27017  

#啟動(dòng)客戶端
./mongo
./mongo --host xxx -u adminUserName -p userPassword --authenticationDatabase admin #可遠(yuǎn)程登錄并指定登錄用戶以及數(shù)據(jù)庫目錄

注意:

關(guān)于日志文件和數(shù)據(jù)存儲(chǔ)路徑的指定一定要是正確的,否則就會(huì)報(bào)如下錯(cuò)誤

ERROR: child process failed, exited with error number 1

mongodb非常的占磁盤空間, 剛啟動(dòng)后要占3-4G左右,如果你用虛擬機(jī)練習(xí),可能空間不夠,導(dǎo)致無法啟動(dòng).可以用 --smallfiles 選項(xiàng)來啟動(dòng), 將會(huì)占用較小空間,大約400M左右.

32位的mongo客戶端貌似會(huì)出現(xiàn)段錯(cuò)誤(segmentation fault)

mongodb服務(wù)器啟動(dòng)時(shí), 默認(rèn)不是需要認(rèn)證的.
要讓用戶生效, 需要啟動(dòng)服務(wù)器時(shí),就指定--auth選項(xiàng).這樣, 操作時(shí),就需要認(rèn)證了(另外也可以在其配置文件中指定)

參數(shù)解釋:

--dbpath 數(shù)據(jù)存儲(chǔ)目錄
--logpath 日志存儲(chǔ)目錄
--port 運(yùn)行端口(默認(rèn)27017)
--fork 后臺(tái)進(jìn)程運(yùn)行
mongodb 命令行 系統(tǒng)與庫表級(jí)命令 查看當(dāng)前的數(shù)據(jù)庫
show dbs/databases

注意: databases 這個(gè)命令只存在在新版本中。

選庫/創(chuàng)建庫

Mongodb的庫是隱式創(chuàng)建,你可以u(píng)se 一個(gè)不存在的庫
然后在該庫下創(chuàng)建collection,即可創(chuàng)建庫

use databaseName
創(chuàng)建collection
db.createCollection("collectionName") 

collection同樣允許隱式創(chuàng)建:

db.collectionName.insert(json);
查看當(dāng)前庫下的collection
show tables/collections 
刪除collection
db.collectionName.drop()
刪除database
db.dropDatabase() # 選擇之后使用
顯示用戶
show users
help命令
db.help()
db.youColl.find().help();
DML命令 insert/save

介紹: mongodb存儲(chǔ)的是文檔,文檔是json格式的對(duì)象.
語法: db.collectionName.isnert(document);

# 增加單篇文檔,默認(rèn)有一個(gè)ID
db.collectionName.insert({title:"nice day"});

# 增加單個(gè)文檔,并指定_id
db.collectionName.insert({_id:8,age:78,name:"lisi"});

# 增加多個(gè)文檔
db.collectionName.insert(
    [
        {time:"friday",study:"mongodb"},
        {_id:9,gender:"male",name:"QQ"}
    ]
)

# insert 與 save的區(qū)別 : 如果插入的數(shù)據(jù)的_id相同,save將會(huì)更新該文檔,而insert將會(huì)報(bào)錯(cuò)
> db.user.find();
{ "_id" : 6, "sex" : "nan" }
{ "_id" : 1, "name" : "zxg" }
{ "_id" : 2, "name" : "user2", "age" : 2 }
{ "_id" : 3, "name" : "user3", "age" : 3 }

> db.user.insert({_id:3,name:"zhouzhou"});
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error index: user.user.$_id_ dup key: { : 3.0 }"
        }
})

> db.user.save({_id:3,name:"zhouzhou"});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.user.find();
{ "_id" : 6, "sex" : "nan" }
{ "_id" : 1, "name" : "zxg" }
{ "_id" : 2, "name" : "user2", "age" : 2 }
{ "_id" : 3, "name" : "zhouzhou" }
remove

語法: db.collection.remove(查詢表達(dá)式, 選項(xiàng));
選項(xiàng)是指 {justOne:true/false},是否只刪一行, 默認(rèn)為false

注意

查詢表達(dá)式依然是個(gè)json對(duì)象

查詢表達(dá)式匹配的行,將被刪掉.

如果不寫查詢表達(dá)式,collections中的所有文檔將被刪掉. 在最新版本的mongodb,必須要寫表達(dá)式才可以刪除

> db.user.find()
{ "_id" : 1, "name" : "user1","age" : 1 }
{ "_id" : 2, "name" : "user2","age" : 2 }
{ "_id" : 3, "name" : "user3","age" : 3 }
{ "_id" : 4, "name" : "user4","age" : 4 }
{ "_id" : 5, "name" : "user5","age" : 5 }
{ "_id" : 6, "sex" : "nan" }

> db.user.remove({name:/user*/i},1)  # 可以通過正則刪除,并且只刪除第1行

> db.user.find()
{ "_id" : 2, "name" : "user2","age" : 2 }
{ "_id" : 3, "name" : "user3","age" : 3 }
{ "_id" : 4, "name" : "user4","age" : 4 }
{ "_id" : 5, "name" : "user5","age" : 5 }
{ "_id" : 6, "sex" : "nan" }

> db.user.remove({name:/user*/i}); # 刪除所有user開頭的

> db.user.remove({age:{$gte:4}}); # 刪除年齡大于或等于4的,這里的查詢表達(dá)式參考下文的find部分,會(huì)有詳細(xì)的說明
update

語法: db.collection.update(criteria,objNew,upsert,multi)

criteria: 設(shè)置查詢條件,用于查詢哪些文檔需要被更新.這里可以組合非常復(fù)雜的查詢條件

objNew: 更新后的對(duì)象

upsert: 設(shè)置為真的時(shí)候如果記錄已經(jīng)存在,更新它,否則新增一個(gè)記錄 默認(rèn)為false

multi: 設(shè)置為真的時(shí)候,將會(huì)更新所有符合查詢條件的文檔.在mongodb中默認(rèn)情況下只會(huì)更新第一條符合的文檔.

1.錯(cuò)誤的更改

> db.user.find();
{ "_id" : 6, "sex" : "nan" }
{ "_id" : 1, "name" : "user1", "age" : 1 }
{ "_id" : 2, "name" : "user2", "age" : 2 }
{ "_id" : 3, "name" : "user3", "age" : 3 }

> db.user.update({name:"user1"},{name:"zxg"});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.user.find();
{ "_id" : 6, "sex" : "nan" }
{ "_id" : 1, "name" : "zxg" }
{ "_id" : 2, "name" : "user2", "age" : 2 }
{ "_id" : 3, "name" : "user3", "age" : 3 }

> db.user.update({name:"xb"},{name:"jyh"},1); # 沒有就添加
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 1,  # upserted 表示更新失敗后插入;
    "nModified" : 0,
    "_id" : ObjectId("55bf37d6ea4ed1b30ffb368d")
})

{ "_id" : ObjectId("55bf3480ea4ed1b30ffb368c"), "name" : "jyh" }

> db.user.update({name:"jyh"},{name:"zxg"},1,1); #全部更改,但是報(bào)錯(cuò),多條更新必須要有表達(dá)式
"writeError" : {
    "code" : 9,
    "errmsg" : "multi update only works with $ operators"
}

結(jié)果: 文檔中的其他列也不見了,改后只有_id和name列了.
即--新文檔直接替換了舊文檔,而不是修改

2.通過修改表達(dá)式正確修改

$set  # 當(dāng)文檔中包含該字段的時(shí)候,更新該字段,如果該文檔中沒有該字段,則為本文檔添加一個(gè)字段.

$unset # 刪除文檔中的一個(gè)字段.

$rename # 重命名某個(gè)列

$inc # 增長某個(gè)列

$setOnInsert # 當(dāng)upsert為true時(shí),并且發(fā)生了insert操作時(shí),可以補(bǔ)充的字段

$push # 將一個(gè)數(shù)字存入一個(gè)數(shù)組,分為三種情況,如果該字段存在,則直接將數(shù)字存入數(shù)組.如果該字段不存在,創(chuàng)建字段并且將數(shù)字插入該數(shù)組.如果更新的字段不是數(shù)組,會(huì)報(bào)錯(cuò)的.

$pushAll # 將多個(gè)數(shù)值一次存入數(shù)組.上面的push只能一個(gè)一個(gè)的存入

$addToSet # 與$push功能相同將一個(gè)數(shù)字存入數(shù)組,不同的是如果數(shù)組中有這個(gè)數(shù)字,將不會(huì)插入,只會(huì)插入新的數(shù)據(jù),同樣也會(huì)有三種情況,與$push相同.

$pop #刪除數(shù)組最后一個(gè)元素

$pull # 刪除數(shù)組中的指定的元素,如果刪除的字段不是數(shù)組,會(huì)報(bào)錯(cuò)

$pullAll # 刪除數(shù)組中的多個(gè)值,跟pushAll與push的關(guān)系類似.

update有以上條件操作符以后才能使用第4參數(shù)進(jìn)行多文檔更新操作;

# set 僅更改文檔中某列的值
db.user.update({name:"user1"},{$set:{name:"zxg"}},0,1); # 把所有name為user1的更改為zxg,僅更改此列

# unset 刪除文檔某一列
db.user.update({name:"zxg"},{$unset:{age:1}})

# 把name為zxg的列的列名name更改為xm
db.user.update({name:"zxg"},{$rename: {name:"xm"}})

# 減少年齡1歲
db.user.update({name:"user2"},{$inc:{age:-1}});

# 增長年齡1歲
db.user.update({name:"user2"},{$inc:{age:1}});

# 更新_id為7的文檔,如果該文檔不存在就創(chuàng)建并增加work字段,并指定值(可多個(gè)值指定),update第三參數(shù)upsert必須為true;
db.user.update({_id:7},{$setOnInsert:{work:"go on"}},1)
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 7 })
數(shù)組操作
# $push
db.test.find()
{ "_id" : 1, "ary" : [ 1, 2, 3, 4 ] }
{ "_id" : 2, "text" : "test" }

db.test.update({_id:1},{$push:{ary:5}}) # 數(shù)組存在 直接壓入,但是這個(gè)地方如果是數(shù)組的話就壓入一個(gè)數(shù)組,并非是合并數(shù)組中的元素

db.test.update({_id:1},{$push:{ary:[8,9,10]}})

db.test.find()
{ "_id" : 2, "text" : "test" }
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5,[8,9,10] ] } # 由此可見push一次只能插入一個(gè)字段,如果想要批量插入的話就緩存pushAll;

db.test.update({_id:2},{$push:{ary:6}}) # 數(shù)組不存在,創(chuàng)建數(shù)組并存入

db.test.find()
{ "_id" : 2, "ary" : [ 6 ], "text" : "test" }
{ "_id" : 1, "ary" : [ 1, 2, 3, 4, 5 ] }

db.test.update({_id:2},{$push:{text:6}})  # 更新字段存在但不是數(shù)組報(bào)錯(cuò)
Cannot apply $push/$pushAll modifier to non-array

# pop
db.user.update({_id:9},{$pop:{test:0}}) # 這里的test無論傳入什么值,都是刪掉test數(shù)組的最后一個(gè)

# $pull
db.user.update({_id:9},{$pull:{test:2}}) #這里的test傳什么值就刪掉什么值
自增唯一性ID方案findandmodify

在查詢的同時(shí)進(jìn)行更改

db.collection.findAndModify({
    query: , // 查詢過濾條件
    
    sort: , //如果多個(gè)文檔符合查詢過濾條件,將以該參數(shù)指定的排列方式選擇出排在首位的對(duì)象
    
    remove: , // Must specify either the remove or the update field. Removes the document specified in the query field. Set this to true to remove the selected document . The default is false.
    
    update: , // Must specify either the remove or the update field. Performs an update of the selected document. The update field employs the same update operators or field: value specifications to modify the selected document.
    
    new: , //  Optional. When true, returns the modified document rather than the original. The findAndModify() method ignores the new option for remove operations. The default is false.
   
    fields: , //Optional. A subset of fields to return. The fields document specifies an inclusion of a field with 1, as in: fields: { : 1, : 1, ... }
   
    upsert:  //Optional. Used in conjunction with the update field. When true, findAndModify() creates a new document if no document matches the query, or if documents match the query, findAndModify() performs an update. To avoid multiple upserts, ensure that the query fields are uniquely indexed.The default is false.
});
db.people.findAndModify({
    query: { name: "Tom", state: "active", rating: { $gt: 10 } },
    sort: { rating: 1 },
    update: { $inc: { score: 1 } }
})

db.runCommand({ findandmodify : "users", 
    query: {age: {$gte: 25}}, 
    sort: {age: -1}, 
    update: {$set: {name: "a2"}, $inc: {age: 2}},
    remove: true
});
自增ID處理
> db.unique.insert({id:0});
WriteResult({ "nInserted" : 1 })
> db.unique.findAndModify({update:{$inc:{id:1}} })
{"id" : 0 }
> db.unique.findAndModify({update:{$inc:{id:1}} })
{"id" : 1 }

//獲得ID以后就插入到需要有自增ID的collection中
深入查詢表達(dá)式 查找某集合所有文檔
db.collection.find()
等值查詢
db.collection.find({filed:value})
返回文檔的某些值
db.user.find({name:"user0"},{age:1})  
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "age" : 0 }  
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "age" : 20 }
#_id是默認(rèn)顯示的,可以傳入_id:0來隱藏它
不等于 $ne
db.collection.find({filed:{$ne:value}})
not in $nin
db.collection.find({filed:{$nin:[value1,value2,value3]}})
數(shù)組查詢$all $in

$all 數(shù)組中必須包含所有給定的查詢的元素

$in 數(shù)組中只要包含給定的查詢?cè)鼐涂梢?/p>

> db.phone.find()
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
> db.phone.find({num:{$all:[1,2]}})
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
> db.phone.find({num:{$all:[1,4]}}) # 同時(shí)包含1,4的沒有數(shù)據(jù)
> db.phone.find({num:{$in:[1,4]}}) # 包含1或4的數(shù)據(jù)
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
查找包含該字段的文檔 $exists
> db.phone.find()
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
{ "_id" : ObjectId("5198e51a20c9b0dc40419388"), "state" : 1 }

> db.phone.find({state:{$exists:1}}) # 存在state字段的
{ "_id" : ObjectId("5198e51a20c9b0dc40419388"), "state" : 1 }

> db.phone.find({state:{$exists:0}}) # 不存在state字段的文檔
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
取模操作 $mod
> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843ba"), "name" : "user8", "age" : 8 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bb"), "name" : "user9", "age" : 9 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "name" : "user0", "age" : 20 }

> db.user.find({age:{$mod:[3,1]}})  # 模三余一
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }

同樣使用 db.user.find("this.age%3==1")這個(gè)語句也能達(dá)到上面的效果,但是不推薦.

滿足一個(gè) $or
> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843ba"), "name" : "user8", "age" : 8 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bb"), "name" : "user9", "age" : 9 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "name" : "user0", "age" : 20 }

> db.user.find({$or:[{name:"user1"},{age:20}]}) # 由此可見or的鍵值為一個(gè)數(shù)組
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "name" : "user0", "age" : 20 }
都不滿足(排除) $nor
> db.user.find({$nor:[{name:"user1"},{age:20}]}) # name不等于user1,以及age不等于20,可以理解為排除;
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843ba"), "name" : "user8", "age" : 8 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bb"), "name" : "user9", "age" : 9 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }
查詢數(shù)組的長度等于給定數(shù)組長度的文檔 $size
> db.phone.find()
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
{ "_id" : ObjectId("5198e51a20c9b0dc40419388"), "state" : 1 }
{ "_id" : ObjectId("519969952b76790566165de2"), "num" : [ 2, 3 ] }

> db.phone.find({num:{$size:4}}) # num數(shù)組長度為4的結(jié)果沒有

> db.phone.find({num:{$size:3}}) # 長度為3的有三個(gè)
{ "_id" : ObjectId("5198e20220c9b0dc40419385"), "num" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("5198e21820c9b0dc40419386"), "num" : [ 4, 2, 3 ] }
{ "_id" : ObjectId("5198e22120c9b0dc40419387"), "num" : [ 1, 2, 5 ] }
自定義的查詢 $where

由bson轉(zhuǎn)換為json,然后再通過回調(diào)函數(shù)去判斷,性能很差,能不用盡量別用

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843ba"), "name" : "user8", "age" : 8 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bb"), "name" : "user9", "age" : 9 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "name" : "user0", "age" : 20 }

> db.user.find({$where:function(){return this.age == 3 || this.age == 4}}) # 回調(diào),進(jìn)入了隱式迭代,然后符合條件的才返回;
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }

# 如今的新版本也可以直接寫where條件
db.goods.find({$where:"this.cat_id != 3 && this.cat_id != 11"});
根據(jù)數(shù)據(jù)類型查詢 $type

在mongodb中每一種數(shù)據(jù)類型都有對(duì)應(yīng)的數(shù)字,我們?cè)谑褂?type的時(shí)候需要使用這些數(shù)字,文檔中給出如下的表示

|類型|編號(hào)|
|:-:|:-:|
|雙精度|1|
|字符串|2|
|對(duì)象|3|
|數(shù)組|4|
|二進(jìn)制數(shù)據(jù)|5|
|對(duì)象 ID|7|
|布爾值|8|
|日期|9|
|空|10|
|正則表達(dá)式|11|
|JavaScript|13|
|符號(hào)|14|
|JavaScript(帶范圍)|15|
|32 位整數(shù)|16|
|時(shí)間戳|17|
|64 位整數(shù)|18|
|最小鍵|255|
|最大鍵|127|

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
{ "_id" : ObjectId("5198c286c686eb50e2c843ba"), "name" : "user8", "age" : 8 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bb"), "name" : "user9", "age" : 9 }
{ "_id" : ObjectId("5198c286c686eb50e2c843bc"), "name" : "user10", "age" : 10 }
{ "_id" : ObjectId("5198c3cac686eb50e2c843bd"), "name" : "user0", "age" : 20 }
{ "_id" : ObjectId("51996ef22b76790566165e47"), "name" : 23, "age" : 33 }
> db.user.find({name:{$type:1}}) # 查找name為雙精度的文檔
{ "_id" : ObjectId("51996ef22b76790566165e47"), "name" : 23, "age" : 33 }
正則表達(dá)式

正則的效率都知道的,得一一解析后再查找,所以效率也是很低;

> db.user.find({name:/user.*/i}) # 查詢name以u(píng)ser開頭不區(qū)分大小寫的文檔 

> db.goods.find({goods_name:/諾基亞.*/},{goods_name:1}); # 以諾基亞開頭的商品
范圍查詢

小于 $lt

大于 $gt

小于或等于 $lte

大于或等于 $gte

limit
> db.user.find({age:{$gte:5}}).limit(3) # 限制返回的是三條數(shù)據(jù)
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b8"), "name" : "user6", "age" : 6 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b9"), "name" : "user7", "age" : 7 }
分頁查詢

使用到skip 和limit方法.skip表示跳過前面的幾個(gè)文檔,limit表示顯示幾個(gè)文檔.

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 2 }
> db.user.find().skip(2).limit(3) # 跳過前兩個(gè)文檔查詢后面的三個(gè)文檔,經(jīng)過測試這兩個(gè)方法的使用順序沒有影響
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
> db.user.find().limit(3).skip(2)
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
sort 排序

在mongodb中排序很簡單,使用sort方法,傳遞給它你想按照哪個(gè)字段的哪種方式排序即可.這里1代表升序,-1代表降序.

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
> db.user.find().sort({age:1})
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
> db.user.find().sort({age:-1})
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 5 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 4 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 3 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
group 分組查詢

mongodb中的group可以實(shí)現(xiàn)類似關(guān)系型數(shù)據(jù)庫中的分組的功能,但是mongodb中的group遠(yuǎn)比關(guān)系型數(shù)據(jù)庫中的group強(qiáng)大,可以實(shí)現(xiàn)map-reduce功能,關(guān)于什么是map-reduce,會(huì)在后續(xù)大數(shù)據(jù)專題里面說明,這里先略過,感興趣的朋友可以百度

group中的json參數(shù)類似這樣{key:{字段:1},initial:{變量:初始值},$reduce:function(doc,prev){函數(shù)代碼}}.

其中的字段代表,需要按哪個(gè)字段分組.
變量表示這一個(gè)分組中會(huì)使用的變量,并且給一個(gè)初始值.可以在后面的$reduce函數(shù)中使用.
$reduce的兩個(gè)參數(shù),分別代表當(dāng)前的文檔和上個(gè)文檔執(zhí)行完函數(shù)后的結(jié)果.如下我們按年齡分組,同級(jí)不同年齡的用戶的多少:

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 2 }

> db.user.group({key:{age:1},initial:{count:0},$reduce:function(doc,prev){prev.count++}}) 
[
        {
                "age" : 0,
                "count" : 1
        },
        {
                "age" : 1,
                "count" : 3
        },
        {
                "age" : 2,
                "count" : 2
        }
]

> db.user.group({key:{age:1},initial:{users:[]},$reduce:function(doc,prev){prev.users.push(doc.name)}}); #由于內(nèi)部是使用js引擎來解析的,所以完全可以通過js語法來操作,這使得雖然mongodb的分組很麻煩但卻很靈活
[
        {
                "age" : 0,
                "users" : [
                        "user0"
                ]
        },
        {
                "age" : 1,
                "users" : [
                        "user1",
                        "user3",
                        "user4"
                ]
        },
        {
                "age" : 2,
                "users" : [
                        "user2",
                        "user5"
                ]
        }
]

# 另外本函數(shù)還有兩個(gè)可選參數(shù) condition 和 finalize

# condition就是分組的條件篩選類似mysql中的having
> db.user.group({key:{age:1},initial:{users:[]},$reduce:function(doc,prev){prev.users.push(doc.name)},condition:{age:{$gt:0}}}) # 篩選出age大于0的;
[
        {
                "age" : 1,
                "users" : [
                        "user1",
                        "user3",
                        "user4"
                ]
        },
        {
                "age" : 2,
                "users" : [
                        "user2",
                        "user5"
                ]
        }
]
count 統(tǒng)計(jì)
> db.goods.count() #不傳參數(shù)就統(tǒng)計(jì)該集合的總數(shù)
31
> db.goods.count({cat_id:3}) # 統(tǒng)計(jì)cat_id=3的總數(shù)
15
distinct 排重
> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 2 }
> db.user.distinct("age") # 略微有點(diǎn)特殊,傳入的參數(shù)直接是字符串,而不是對(duì)象;
[ 0, 1, 2 ]
子文檔查詢 $elemMatch與對(duì)象中的屬性
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }

db.scores.find(
   { results: { $elemMatch: { $gte: 80, $lt: 85 } } } #查詢r(jià)esults文檔中的元素同時(shí)滿足即大于80并且又小于85的,注意此處只要其中一個(gè)元素滿足這個(gè)查詢就會(huì)返回
)

{ "_id" : 1, "results" : [ 82, 85, 88 ] }
> db.user.find();
{ "_id" : ObjectId("55c070a02cc8cec37073a1d9"), "name" : "zxg", "age" : 28, "hobby" : { "life" : [ "電影", "小說", "漫畫" ], "work" : [ "發(fā)呆", "發(fā)呆2" ], "home" : "玩耍" } }
{ "_id" : ObjectId("55c070a52cc8cec37073a1da"), "name" : "jyh", "age" : 28, "hobby" : { "life" : [ "賣萌", "養(yǎng)兔子", "做家務(wù)" ], "work" : [ "郁悶", "郁悶2" ], "home" : "賣萌" } }
{ "_id" : ObjectId("55c072db2cc8cec37073a1db"), "name" : "jyh", "age" : 28, "hobby" : [ { "life" : [ "賣萌", "養(yǎng)兔子", "做家務(wù)" ] }, { "work" : [ "郁悶", "郁悶2" ] }, { "home" : "賣萌" } ] }

> db.user.find({hobby:{$elemMatch:{home:"賣萌"}}}) # 注意上文的結(jié)構(gòu),必須是要在數(shù)組中才可以查出
{ "_id" : ObjectId("55c072db2cc8cec37073a1db"), "name" : "jyh", "age" : 28, "hobby" : [ { "life" : [ "賣萌", "養(yǎng)兔子", "做家務(wù)" ] }, { "work" : [ "郁悶", "郁悶2" ] }, { "home" : "賣萌" } ] }

> db.user.find({"hobby.home":"賣萌"}) # 注意,hobby.home類似js中對(duì)象與屬性的操作方式,但是要加上引號(hào),否則會(huì)報(bào)錯(cuò)
{ "_id" : ObjectId("55c070a52cc8cec37073a1da"), "name" : "jyh", "age" : 28, "hobby" : { "life" : [ "賣萌", "養(yǎng)兔子", "做家務(wù)" ], "work" : [ "郁悶", "郁悶2" ], "home" : "賣萌" } }
{ "_id" : ObjectId("55c072db2cc8cec37073a1db"), "name" : "jyh", "age" : 28, "hobby" : [ { "life" : [ "賣萌", "養(yǎng)兔子", "做家務(wù)" ] }, { "work" : [ "郁悶", "郁悶2" ] }, { "home" : "賣萌" } ] }
查詢實(shí)例

以下查詢基于ecshop網(wǎng)站的數(shù)據(jù)查詢

# 本店價(jià)格低于或等于100元的商品($lte)
db.goods.find({shop_price:{$lte:100}},{goods_name:1,shop_price:1});

# 取出第4欄目或第11欄目的商品($in)
 db.goods.find({cat_id:{$in:[4,11]}},{goods_name:1,shop_price:1});

# 取出100<=價(jià)格<=500的商品($and)
db.goods.find({$and:[{"shop_price":{$gte:100}},{"shop_price":{$lte:500}}]},{_id:0,shop_price:1})

# 取出不屬于第3欄目且不屬于第11欄目的商品($and $nin和$nor分別實(shí)現(xiàn))
db.goods.find({$and:[{cat_id:{$ne:3}},{cat_id:{$ne:11}}]},{_id:0,cat_id:1})
db.goods.find({cat_id:{$nin:[3,11]}},{_id:0,cat_id:1})
db.goods.find({$nor:[{cat_id:3},{cat_id:11}]},{_id:0,cat_id:1})

# 取出價(jià)格大于100且小于300,或者大于2000且小于5000的商品()
db.goods.find({$or:[{$and:[{shop_price:{$gt:100}}, {shop_price:{$lt:300} }]}, {$and:[{shop_price:{$gt:2000}}, {shop_price:{$lt:5000} }] } ] },{_id:0,shop_price:1} )

# 取出所有g(shù)oods_id為偶數(shù)的商品;
db.goods.find({goods_id:{$mod:[2,0]}},{_id:0,goods_id:1})

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/18811.html

相關(guān)文章

  • mysql - 收藏集 - 掘金

    摘要:步優(yōu)化以及其它數(shù)據(jù)庫后端掘金原文鏈接在發(fā)表了一篇簡潔有效有趣和令人信服的分鐘教程描述了如何進(jìn)行優(yōu)化。關(guān)于的七種后端掘金對(duì)于的,在學(xué)習(xí)起來可能是比較亂的。 5 步優(yōu)化 MongoDB 以及其它數(shù)據(jù)庫 - 后端 - 掘金原文鏈接 Jared Rosoff 在 Scale Out Camp 發(fā)表了一篇簡潔、有效、有趣和令人信服的《8 分鐘 MongoDB 教程》描述了如何進(jìn)行 MongoDB...

    Donald 評(píng)論0 收藏0
  • nodejs 基礎(chǔ)整合

    摘要:基礎(chǔ)篇整合最近有朋友也想學(xué)習(xí)相關(guān)方面的知識(shí),如果你是后端想接近前端,作為一門跑在服務(wù)端的語言從這里入門再好不過了。事件驅(qū)動(dòng)機(jī)制是通過內(nèi)部單線程高效率地維護(hù)事件循環(huán)隊(duì)列來實(shí)現(xiàn)的,沒有多線程的資源占用和上下文的切換。 nodeJs 基礎(chǔ)篇整合 最近有朋友也想學(xué)習(xí)nodeJs相關(guān)方面的知識(shí),如果你是后端想接近前端,node作為一門跑在服務(wù)端的JS語言從這里入門再好不過了。如果你正好喜歡前端,...

    lemanli 評(píng)論0 收藏0
  • nodejs 基礎(chǔ)整合

    摘要:基礎(chǔ)篇整合最近有朋友也想學(xué)習(xí)相關(guān)方面的知識(shí),如果你是后端想接近前端,作為一門跑在服務(wù)端的語言從這里入門再好不過了。事件驅(qū)動(dòng)機(jī)制是通過內(nèi)部單線程高效率地維護(hù)事件循環(huán)隊(duì)列來實(shí)現(xiàn)的,沒有多線程的資源占用和上下文的切換。 nodeJs 基礎(chǔ)篇整合 最近有朋友也想學(xué)習(xí)nodeJs相關(guān)方面的知識(shí),如果你是后端想接近前端,node作為一門跑在服務(wù)端的JS語言從這里入門再好不過了。如果你正好喜歡前端,...

    lentrue 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<