MongoDB快速上手指南:數(shù)據(jù)庫(kù)操作常用命令CRUD
2.1 數(shù)據(jù)庫(kù)操作
默認(rèn)保留的數(shù)據(jù)庫(kù)
- admin: 從權(quán)限角度考慮, 這是
root
數(shù)據(jù)庫(kù), 如果將一個(gè)用戶添加到這個(gè)數(shù)據(jù)庫(kù), 這個(gè)用戶自動(dòng)繼承所有數(shù)據(jù)庫(kù)的權(quán)限, 一些特定的服務(wù)器端命令也只能從這個(gè)數(shù)據(jù)庫(kù)運(yùn)行, 比如列出所有的數(shù)據(jù)庫(kù)或者關(guān)閉服務(wù)器 - local: 數(shù)據(jù)永遠(yuǎn)不會(huì)被復(fù)制, 可以用來(lái)存儲(chǔ)限于本地的單臺(tái)服務(wù)器的集合 (部署集群, 分片等)
- config: Mongo 用于分片設(shè)置時(shí),
config
數(shù)據(jù)庫(kù)在內(nèi)部使用, 用來(lái)保存分片的相關(guān)信息> show dbs admin 0.000GB config 0.000GB local 0.000GB > use articledb switched to db articledb > show dbs admin 0.000GB config 0.000GB local 0.000GB 復(fù)制代碼
當(dāng)我們創(chuàng)建了一個(gè)數(shù)據(jù)庫(kù)后再進(jìn)行查看會(huì)發(fā)現(xiàn),我們創(chuàng)建的數(shù)據(jù)庫(kù)并沒(méi)有顯示出來(lái),這是由于MongoDD的存儲(chǔ)機(jī)制決定的
當(dāng)使用
use articledb
的時(shí)候.articledb
其實(shí)存放在內(nèi)存之中, 當(dāng)articledb
中存在一個(gè) collection 之后, mongo 才會(huì)將這個(gè)數(shù)據(jù)庫(kù)持久化到硬盤之中.
javascript copyable" lang="JavaScript">> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use articledb
switched to db articledb
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> db.articledb.insertOne({"a": 3})
{
"acknowledged" : true,
"insertedId" : ObjectId("62e128b6a70e7344a5139207")
}
> show dbs
admin 0.000GB
articledb 0.000GB
config 0.000GB
local 0.000GB
復(fù)制代碼
另外: 數(shù)據(jù)庫(kù)名可以是滿足以下條件的任意UTF-8字符串。
- 不能是空字符串("")。
- 不得含有
' '
空格)、.
、$
、/
、和
0
(空字符)。 - 應(yīng)全部小寫。
- 最多64字節(jié)。
集合操作與數(shù)據(jù)庫(kù)操作類似,這里不再單獨(dú)演示
2.2 文檔基本 CRUD
官方文檔: docs.mongodb.com/manual/crud…
2.2.1 創(chuàng)建 Create
Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection automatically.
文檔的數(shù)據(jù)結(jié)構(gòu)和 JSON 基本一樣。
所有存儲(chǔ)在集合中的數(shù)據(jù)都是 BSON 格式。
BSON 是一種類似 JSON 的二進(jìn)制形式的存儲(chǔ)格式,是 Binary JSON 的簡(jiǎn)稱
- 使用
db.
向集合中添加一個(gè)文檔, 參數(shù)一個(gè) json 格式的文檔 -db.collection.insertOne() 用于向集合插入一個(gè)新文檔,語(yǔ)法格式如下:.insertOne() db.collection.insertOne(
, { writeConcern: } ) 復(fù)制代碼 - 使用
db.
向集合中添加多個(gè)文檔, 參數(shù)為 json 文檔數(shù)組 db.collection.insertMany() 用于向集合插入一個(gè)多個(gè)文檔,語(yǔ)法格式如下:.insertMany()
db.collection.insertMany(
[ 1> , 2>, ... ],
{
writeConcern: ,
ordered: <boolean>
}
)
復(fù)制代碼
參數(shù)說(shuō)明:
- document:要寫入的文檔。
- writeConcern:寫入策略,默認(rèn)為 1,即要求確認(rèn)寫操作,0 是不要求。
- ordered:指定是否按順序?qū)懭?,默認(rèn) true,按順序?qū)懭?/li>
我們平時(shí)使用最多的只有
document
這一個(gè)字段
# 插入單條數(shù)據(jù)
> var document = db.collection.insertOne({"a": 3})
> document
{
"acknowledged" : true,
"insertedId" : ObjectId("571a218011a82a1d94c02333")
}
# 插入多條數(shù)據(jù)
> var res = db.collection.insertMany([{"b": 3}, {'c': 4}])
> res
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("571a22a911a82a1d94c02337"),
ObjectId("571a22a911a82a1d94c02338")
]
}
復(fù)制代碼
還可以通過(guò)js函數(shù)方式批量插入文檔:
1、先創(chuàng)建數(shù)組 2、將數(shù)據(jù)放在數(shù)組中 3、一次 insert 到集合中
var arr = [];
for(var i=1 ; i<=20000 ; i++){
arr.push({num:i});
}
db.numbers.insert(arr);
復(fù)制代碼
注:當(dāng)我們向 collection
中插入 document
文檔時(shí), 如果沒(méi)有給文檔指定 _id
屬性, 那么數(shù)據(jù)庫(kù)會(huì)為文檔自動(dòng)添加 _id
field, 并且值類型是 ObjectId(blablabla)
, 就是文檔的唯一標(biāo)識(shí), 類似于 relational database 里的 primary key
- mongo 中的數(shù)字, 默認(rèn)情況下是 double 類型, 如果要存整型, 必須使用函數(shù)
NumberInt(整型數(shù)字)
, 否則取出來(lái)就有問(wèn)題了- 插入當(dāng)前日期可以使用
new Date()
如果某條數(shù)據(jù)插入失敗, 將會(huì)終止插入, 但已經(jīng)插入成功的數(shù)據(jù)不會(huì)回滾掉. 因?yàn)榕坎迦胗捎跀?shù)據(jù)較多容易出現(xiàn)失敗, 因此, 可以使用 try catch
進(jìn)行異常捕捉處理, 測(cè)試的時(shí)候可以不處理.如:
try {
// 插入多條記錄
db.comment.insertMany([
{"_id":"1","articleid":"100001","content":"我們不應(yīng)該把清晨浪費(fèi)在手機(jī)上,健康很重要,一杯溫水幸福你我他。","userid":"1002","nickname":"相忘于江湖","createdatetime":new Date("2019-08-05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"},
{"_id":"2","articleid":"100001","content":"我夏天空腹喝涼開水,冬天喝溫開水","userid":"1005","nickname":"伊人憔悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"},
{"_id":"3","articleid":"100001","content":"我一直喝涼開水,冬天夏天都喝。","userid":"1004","nickname":"杰克船長(zhǎng)","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"},
{"_id":"4","articleid":"100001","content":"專家說(shuō)不能空腹吃飯,影響健康。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"},
{"_id":"5","articleid":"100001","content":"研究表明,剛燒開的水千萬(wàn)不能喝,因?yàn)闋C嘴。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08-06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"}
]);
} catch (e) {
print (e);
}
復(fù)制代碼
2.2.2 查詢 Read
更多查詢可以看2.4節(jié)和2.5節(jié)
- 使用
db.
方法對(duì)集合進(jìn)行查詢, 接受一個(gè) json 格式的查詢條件. 返回的是一個(gè)數(shù)組.find() db.
查詢集合中符合條件的第一個(gè)文檔, 返回的是一個(gè)對(duì)象.findOne()
// 插入多條記錄
> db.comment.insertMany([
{"_id":"1","articleid":"100001","content":"我們不應(yīng)該把清晨浪費(fèi)在手機(jī)上,健康很重要,一杯溫水幸福你我他。","userid":"1002","nickname":"相忘于江湖","createdatetime":new Date("2019-08-05T22:08:15.522Z"),"likenum":NumberInt(1000),"state":"1"},
{"_id":"2","articleid":"100001","content":"我夏天空腹喝涼開水,冬天喝溫開水","userid":"1005","nickname":"伊人憔悴","createdatetime":new Date("2019-08-05T23:58:51.485Z"),"likenum":NumberInt(888),"state":"1"},
{"_id":"3","articleid":"100001","content":"我一直喝涼開水,冬天夏天都喝。","userid":"1004","nickname":"杰克船長(zhǎng)","createdatetime":new Date("2019-08-06T01:05:06.321Z"),"likenum":NumberInt(666),"state":"1"},
{"_id":"4","articleid":"100001","content":"專家說(shuō)不能空腹吃飯,影響健康。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08-06T08:18:35.288Z"),"likenum":NumberInt(2000),"state":"1"},
{"_id":"5","articleid":"100001","content":"研究表明,剛燒開的水千萬(wàn)不能喝,因?yàn)闋C嘴。","userid":"1003","nickname":"凱撒","createdatetime":new Date("2019-08-06T11:01:02.521Z"),"likenum":NumberInt(3000),"state":"1"}
]);
{
"acknowledged" : true,
"insertedIds" : [
"1",
"2",
"3",
"4",
"5"
]
}
// 只返回查詢到的第一條數(shù)據(jù)
> db.comment.findOne({"articleid":"100001"})
{
"_id" : "1",
"articleid" : "100001",
"content" : "我們不應(yīng)該把清晨浪費(fèi)在手機(jī)上,健康很重要,一杯溫水幸福你我他。",
"userid" : "1002",
"nickname" : "相忘于江湖",
"createdatetime" : ISODate("2019-08-05T22:08:15.522Z"),
"likenum" : 1000,
"state" : "1"
}
// 等價(jià)于
db.comment.find({"articleid":"100001"}).limit(1)
復(fù)制代碼
如果我們不需要那么多的字段,我們可以在查詢條件后面再跟上需要查詢的字段,1
表示顯示指定的字段,其中_id
是默認(rèn)顯示的,我們指定0
表示強(qiáng)制不顯示
// 只顯示articleid字段
> db.comment.find({"articleid":"100001"},{"articleid":1}).limit(1)
{ "_id" : "1", "articleid" : "100001" }
// 強(qiáng)制_id不顯示
> db.comment.find({"articleid":"100001"},{"articleid":1,"_id":0}).limit(1)
{ "articleid" : "100001" }
復(fù)制代碼
可以使用 $in
操作符表示范圍查詢
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
復(fù)制代碼
多個(gè)查詢條件用逗號(hào)分隔, 表示 AND
的關(guān)系
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
復(fù)制代碼
等價(jià)于下面 sql 語(yǔ)句
SELECT * FROM inventory WHERE status = "A" AND qty < 30
復(fù)制代碼
使用 $or
操作符表示后邊數(shù)組中的條件是OR的關(guān)系
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
復(fù)制代碼
等價(jià)于下面 sql 語(yǔ)句
SELECT * FROM inventory WHERE status = "A" OR qty < 30
復(fù)制代碼
聯(lián)合使用 AND
和 OR
的查詢語(yǔ)句
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
復(fù)制代碼
在 terminal 中查看結(jié)果可能不是很方便, 所以我們可以用 pretty()
來(lái)幫助閱讀
db.inventory.find().pretty()
復(fù)制代碼
匹配內(nèi)容
db.posts.find({
comments: {
$elemMatch: {
user: 'Harry Potter'
}
}
}).pretty()
// 正則表達(dá)式
db..find({ content : /once/ })
復(fù)制代碼
創(chuàng)建索引
db.posts.createIndex({
{ title : 'text' }
})
// 文本搜索
// will return document with title "Post One"
// if there is no more posts created
db.posts.find({
$text : {
$search : ""Post O""
}
}).pretty()
復(fù)制代碼
2.2.3 更新 Update
- 使用
db.
方法修改一個(gè)匹配.updateOne( , , )
條件的文檔 - 使用
db.
方法修改所有匹配.updateMany( , , )
條件的文檔 - 使用
db.
方法替換一個(gè)匹配.replaceOne( , , )
條件的文檔 db.
默認(rèn)情況下會(huì)使用新對(duì)象替換舊對(duì)象.update(查詢對(duì)象, 新對(duì)象)
其中
參數(shù)與查詢方法中的條件參數(shù)用法一致
覆蓋修改,會(huì)將其他的值清除
// nModified1表示有一條記錄被修改
> db.comment.update({"_id":"1"}, {"likenum":NumberInt(1001)})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
// 可以看到其他字段的值不見了
> db.comment.find()
{ "_id" : "1", "likenum" : 1001 }
{ "_id" : "2", "articleid" : "100001", "content" : "我夏天空腹喝涼開水,冬天喝溫開水", "userid" : "1005", "nickname" : "伊人憔悴", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 888, "state" : "1" }
{ "_id" : "3", "articleid" : "100001", "content" : "我一直喝涼開水,冬天夏天都喝。", "userid" : "1004", "nickname" : "杰克船長(zhǎng)", "createdatetime" : ISODate("2019-08-06T01:05:06.321Z"), "likenum" : 666, "state" : "1" }
{ "_id" : "4", "articleid" : "100001", "content" : "專家說(shuō)不能空腹吃飯,影響健康。", "userid" : "1003", "nickname" : "凱撒", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "研究表明,剛燒開的水千萬(wàn)不能喝,因?yàn)闋C嘴。", "userid" : "1003", "nickname" : "凱撒", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }
復(fù)制代碼
局部修改,只修改我們修改的部分,其他字段不受影響
如果需要修改指定的屬性, 而不是替換需要用“修改操作符”來(lái)進(jìn)行修改
$set
修改文檔中的制定屬性
// 發(fā)現(xiàn)局部修改后其他字段并不受影響
> db.comment.update({ "_id": "2" }, {$set:{ "likenum": NumberInt(1001) }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.comment.find()
{ "_id" : "1", "likenum" : 1001 }
{ "_id" : "2", "articleid" : "100001", "content" : "我夏天空腹喝涼開水,冬天喝溫開水", "userid" : "1005", "nickname" : "伊人憔悴", "createdatetime" : ISODate("2019-08-05T23:58:51.485Z"), "likenum" : 1001, "state" : "1" }
{ "_id" : "3", "articleid" : "100001", "content" : "我一直喝涼開水,冬天夏天都喝。", "userid" : "1004", "nickname" : "杰克船長(zhǎng)", "createdatetime" : ISODate("2019-08-06T01:05:06.321Z"), "likenum" : 666, "state" : "1" }
{ "_id" : "4", "articleid" : "100001", "content" : "專家說(shuō)不能空腹吃飯,影響健康。", "userid" : "1003", "nickname" : "凱撒", "createdatetime" : ISODate("2019-08-06T08:18:35.288Z"), "likenum" : 2000, "state" : "1" }
{ "_id" : "5", "articleid" : "100001", "content" : "研究表明,剛燒開的水千萬(wàn)不能喝,因?yàn)闋C嘴。", "userid" : "1003", "nickname" : "凱撒", "createdatetime" : ISODate("2019-08-06T11:01:02.521Z"), "likenum" : 3000, "state" : "1" }
復(fù)制代碼
其中最常用的修改操作符即為$set
和$unset
,分別表示賦值和取消賦值.
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
db.inventory.updateMany(
{ qty: { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
復(fù)制代碼
- uses the
$set
operator to update the value of thesize.uom
field to"cm"
and the value of thestatus
field to"P"
,- uses the
$currentDate
operator to update the value of thelastModified
field to the current date. IflastModified
field does not exist,$currentDate
will create the field. See$currentDate
for details.
db.
方法替換除 _id
屬性外的所有屬性, 其
參數(shù)應(yīng)為一個(gè)全新的文檔.
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
復(fù)制代碼
批量修改
在后面添加{multi: true}
即可
// 默認(rèn)會(huì)修改第一條
db.commnet.update({ userid: "30", { $set {username: "guest"} } })
// 修改所有符合條件的數(shù)據(jù)
db.commnet.update( { userid: "30", { $set {username: "guest"} } }, {multi: true} )
復(fù)制代碼
列值增長(zhǎng)的修改
如果我們想實(shí)現(xiàn)對(duì)某列值在原有值的基礎(chǔ)上進(jìn)行增加或減少, 可以使用 $inc
運(yùn)算符來(lái)實(shí)現(xiàn)
db.commnet.update({ _id: "3", {$inc: {likeNum: NumberInt(1)}} })
復(fù)制代碼
修改操作符
2.2.4 刪除 Delete
db.collection.remove()
通過(guò)添加刪除規(guī)則進(jìn)行刪除- 使用
db.collection.deleteMany()
方法刪除所有匹配的文檔. - 使用
db.collection.deleteOne()
方法刪除單個(gè)匹配的文檔. db.collection.drop()
db.dropDatabase()
只刪除一條記錄
如果不加后面的限制會(huì)刪除所有匹配的記錄
以下語(yǔ)句可以將數(shù)據(jù)全部刪除,請(qǐng)慎用
db.comment.remove({})
復(fù)制代碼
Delete operations do not drop indexes, even if deleting all documents from a collection.
一般數(shù)據(jù)庫(kù)中的數(shù)據(jù)都不會(huì)真正意義上的刪除, 會(huì)添加一個(gè)字段, 用來(lái)表示這個(gè)數(shù)據(jù)是否被刪除
2.3 文檔排序和投影 (sort & projection)
2.3.1 排序 Sort
在查詢文檔內(nèi)容的時(shí)候, 默認(rèn)是按照 _id
進(jìn)行排序
我們可以用 $sort
更改文檔排序規(guī)則
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
復(fù)制代碼
For the field or fields to sort by, set the sort order to 1
or -1
to specify an ascending or descending sort respectively, as in the following example:
db.users.aggregate(
[
{ $sort : { age : -1, posts: 1 } }
// ascending on posts and descending on age
]
)
復(fù)制代碼
$sort
Operator and Memory
$sort
+ $limit
Memory Optimization
When a $sort
precedes a $limit
and there are no intervening stages that modify the number of documents, the optimizer can coalesce the $limit
into the $sort
. This allows the $sort
operation to only maintain the top n
results as it progresses, where n
is the specified limit, and ensures that MongoDB only needs to store n
items in memory. This optimization still applies when allowDiskUse
is true
and the n
items exceed the aggregation memory limit.
Optimizations are subject to change between releases.
有點(diǎn)類似于用 heap 做 topK 這種問(wèn)題, 只維護(hù) k 個(gè)大小的 heap, 會(huì)加速 process
舉個(gè)栗子:
db.posts.find().sort({ title : -1 }).limit(2).pretty()
復(fù)制代碼
2.3.2 投影 Projection
有些情況, 我們對(duì)文檔進(jìn)行查詢并不是需要所有的字段, 比如只需要 id 或者 用戶名, 我們可以對(duì)文檔進(jìn)行“投影”
1
- display0
- dont display
> db.users.find( {}, {username: 1} )
> db.users.find( {}, {age: 1, _id: 0} )
復(fù)制代碼
2.4 分頁(yè)查詢
2.4.1 統(tǒng)計(jì)查詢
統(tǒng)計(jì)查詢使用count()方法,語(yǔ)法如下:
db.collection.count(query, options)
復(fù)制代碼
參數(shù):
提示: 可選項(xiàng)暫時(shí)不使用。
【示例】
(1)統(tǒng)計(jì)所有記錄數(shù): 統(tǒng)計(jì)comment集合的所有的記錄數(shù):
(2)按條件統(tǒng)計(jì)記錄數(shù):例如:統(tǒng)計(jì)userid為1003的記錄條數(shù)
提示: 默認(rèn)情況下 count() 方法返回符合條件的全部記錄條數(shù)。
2.4.2 分頁(yè)列表查詢
可以使用limit()方法來(lái)讀取指定數(shù)量的數(shù)據(jù),使用skip()方法來(lái)跳過(guò)指定數(shù)量的數(shù)據(jù)
基本語(yǔ)法如下所示:
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
復(fù)制代碼
2.4.3 排序查詢
sort() 方法對(duì)數(shù)據(jù)進(jìn)行排序,sort() 方法可以通過(guò)參數(shù)指定排序的字段,并使用 1 和 -1 來(lái)指定排序的方式,其中 1 為升序排列,而 -1 是用 于降序排列。
語(yǔ)法如下所示:
db.COLLECTION_NAME.find().sort({KEY:1})
或
db.集合名稱.find().sort(排序方式)
復(fù)制代碼
例如: 對(duì)userid降序排列,并對(duì)訪問(wèn)量進(jìn)行升序排列
提示: skip(), limilt(), sort()三個(gè)放在一起執(zhí)行的時(shí)候,執(zhí)行的順序是先 sort(), 然后是 skip(),最后是顯示的 limit(),和命令編寫順序無(wú)關(guān)。
2.5 其他查詢方式
2.5.1 正則表達(dá)式(模糊查詢)
MongoDB的模糊查詢是通過(guò)正則表達(dá)式的方式實(shí)現(xiàn)的。格式為
$ db.collection.find({field:/正則表達(dá)式/})
$ db.collection.find({字段:/正則表達(dá)式/})
復(fù)制代碼
提示:正則表達(dá)式是js的語(yǔ)法,直接量的寫法。 例如,我要查詢?cè)u(píng)論內(nèi)容包含“開水”的所有文檔,代碼如下:
如果要查詢?cè)u(píng)論的內(nèi)容中以“專家”開頭的,代碼如下:
附錄:常用的正則表達(dá)式
2.5.2 比較查詢
<
, <=
, >
, >=
這些操作符也是很常用的, 格式如下:
其實(shí)這些字符就是對(duì)應(yīng)JS里面的:gt(great than)、lt(less than)、gte(great than equal )、lte(less than equal )、ne(not equal)
db.collection.find({ "field" : { $gt: value }}) // 大于: field > value
db.collection.find({ "field" : { $lt: value }}) // 小于: field < value
db.collection.find({ "field" : { $gte: value }}) // 大于等于: field >= value
db.collection.find({ "field" : { $lte: value }}) // 小于等于: field <= value
db.collection.find({ "field" : { $ne: value }}) // 不等于: field != value
復(fù)制代碼
示例:查詢?cè)u(píng)論點(diǎn)贊數(shù)量大于700的記錄
2.5.3 包含查詢
包含使用 $in
操作符. 示例:查詢?cè)u(píng)論的集合中 userid
字段包含 1003
或 1004
的文檔
db.comment.find({userid:{$in:["1003","1004"]}})
復(fù)制代碼
不包含使用 $nin
操作符. 示例:查詢?cè)u(píng)論集合中 userid
字段不包含 1003
和 1004
的文檔
db.comment.find({userid:{$nin:["1003","1004"]}})
復(fù)制代碼
2.5.4 條件連接查詢
我們?nèi)绻枰樵兺瑫r(shí)滿足兩個(gè)以上條件,需要使用$and操作符將條件進(jìn)行關(guān)聯(lián)。(相當(dāng)于SQL的and) 格式為:
$and:[ { },{ },{ } ]
復(fù)制代碼
示例:查詢?cè)u(píng)論集合中l(wèi)ikenum大于等于700 并且小于2000的文檔:
db.comment.find({$and:[{likenum:{$gte:NumberInt(700)}},{likenum:{$lt:NumberInt(2000)}}]})
復(fù)制代碼
如果兩個(gè)以上條件之間是或者的關(guān)系,我們使用 操作符進(jìn)行關(guān)聯(lián),與前面 and的使用方式相同 格式為:
$or:[ { },{ },{ } ]
復(fù)制代碼
示例:查詢?cè)u(píng)論集合中userid為1003,或者點(diǎn)贊數(shù)小于1000的文檔記錄
db.comment.find({$or:[ {userid:"1003"} ,{likenum:{$lt:1000} }]})
復(fù)制代碼
2.5.5 foreach查詢
我們知道這些查詢語(yǔ)句其實(shí)就是js
的語(yǔ)法格式,所有在查詢得到結(jié)果后我們也可以通過(guò)forEach
函數(shù)對(duì)結(jié)果進(jìn)行遍歷
db.posts.find().forEach(
fucntion(doc) {
print('Blog Post: ' + doc.title)
})
// 也可以通過(guò)箭頭函數(shù)簡(jiǎn)化一下
db.comment.find().forEach((it)=> {
print(it._id)
});
復(fù)制代碼
2.5.6 地理位置查詢
請(qǐng)查看MongoDB中文文檔:地理空間查詢 - MongoDB-CN-Manual (mongoing.com)
2.6 常用命令小結(jié)
選擇切換數(shù)據(jù)庫(kù):use articledb
插入數(shù)據(jù):db.comment.insert({bson數(shù)據(jù)})
查詢所有數(shù)據(jù):db.comment.find();
條件查詢數(shù)據(jù):db.comment.find({條件})
查詢符合條件的第一條記錄:db.comment.findOne({條件})
查詢符合條件的前幾條記錄:db.comment.find({條件}).limit(條數(shù))
查詢符合條件的跳過(guò)的記錄:db.comment.find({條件}).skip(條數(shù))
修改數(shù)據(jù):db.comment.update({條件},{修改后的數(shù)據(jù)})
或
db.comment.update({條件},{$set:{要修改部分的字段:數(shù)據(jù)})
修改數(shù)據(jù)并自增某字段值:db.comment.update({條件},{$inc:{自增的字段:步進(jìn)值}})
刪除數(shù)據(jù):db.comment.remove({條件})
統(tǒng)計(jì)查詢:db.comment.count({條件})
模糊查詢:db.comment.find({字段名:/正則表達(dá)式/})
條件比較運(yùn)算:db.comment.find({字段名:{$gt:值}})
包含查詢:db.comment.find({字段名:{$in:[值1, 值2]}})
或
db.comment.find({字段名:{$nin:[值1, 值2]}})
條件連接查詢:db.comment.find({$and:[{條件1},{條件2}]})
或
db.comment.find({$or:[{條件1},{條件2}]})
復(fù)制代碼
3. 文檔間的對(duì)應(yīng)關(guān)系
- 一對(duì)一 (One To One)
- 一對(duì)多/多對(duì)一(one to many / many to one)
- 多對(duì)多 (Many To Many)
作者:是小梁同學(xué)呀
來(lái)源:稀土掘金
版權(quán)聲明:
本站所有文章和圖片均來(lái)自用戶分享和網(wǎng)絡(luò)收集,文章和圖片版權(quán)歸原作者及原出處所有,僅供學(xué)習(xí)與參考,請(qǐng)勿用于商業(yè)用途,如果損害了您的權(quán)利,請(qǐng)聯(lián)系網(wǎng)站客服處理。