MongoDB 集合与文档的相关操作
一、集合
(1) MongoDB创建库
> use test #如果数据库不存在,则创建数据库,否则切换到指定数据库。 switched to db test > db #查看当前所在的库 test
(2)MongoDB删除库
> show dbs admin 0.000GB local 0.000GB test 0.000GB > use test switched to db test > db.dropDatabase() #删除当前库 { "dropped" : "test", "ok" : 1 } > show dbs admin 0.000GB local 0.000GB
(3)创建person集合
> use test switched to db test > db.createCollection("person") #创建集合:db.createCollection(name, options) option为可选参数 { "ok" : 1 }
(4)删除person集合
> db.person.drop() #该命令会直接删除整个集合和其中的数据以及索引,包括副本集上的相应集合,不可恢复,生产环境上请谨慎使用
(5)查询集合帮助文档
> db.person.help() #查看集合person的帮助文档
(6)重命名集合
> use test switched to db test > db.person.renameCollection("person1") #重命名集合person为person1 { "ok" : 1 }
(7)查询集合列表
> show collections person > show tables person
(8)集合插入数据
> db.person.insert({"name":"jack","age":25}) WriteResult({ "nInserted" : 1 }) > db.person.insert({"name":"jack2","age":27}) WriteResult({ "nInserted" : 1 })
(9)查询集合数据
> db.person.find() { "_id" : ObjectId("60acfe46dac5c3b46e2b9acf"), "name" : "jack", "age" : 25 } { "_id" : ObjectId("60acfe88dac5c3b46e2b9ad0"), "name" : "jack2", "age" : 27 }
(10)查询集合的数据条目
> db.person.count() 2
(11)查询集合数据空间大小
> db.person.dataSize() 101
(12) 查询当前聚集集合所在db
> db.person.getDB() test
(13) 查询当前聚集集合状态,即集合统计信息
> db.person.stats() { "ns" : "test.person1", "count" : 2, "size" : 101, "avgObjSize" : 50, "storageSize" : 32768, "capped" : false, "wiredTiger" : { "metadata" : { "formatVersion" : 1 }, "creationString" : "allocation_size=4KB,app_metadata=(formatVersion=1),block_allocation=best,block_compressor=snappy,cache_resident=0,checkpoint=(WiredTigerCheckpoint.3=(addr=\"018481e4971f0e908581e4ecee3cf38681e40c5855ca808080e25fc0e20fc0\",order=3,time=1621950108,size=12288,write_gen=4)),checkpoint_lsn=(1,63488),checksum=on,collator=,columns=,dictionary=0,format=btree,huffman_key=,huffman_value=,id=22,internal_item_max=0,internal_key_max=0,internal_key_truncate=,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=0,prefix_compression_min=4,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,value_format=u,version=(major=1,minor=1)", "type" : "file", "uri" : "statistics:table:test/collection-19--508156554362741292", "LSM" : { "bloom filters in the LSM tree" : 0, "bloom filter false positives" : 0, "bloom filter hits" : 0, "bloom filter misses" : 0, "bloom filter pages evicted from cache" : 0, "bloom filter pages read into cache" : 0, "total size of bloom filters" : 0, "sleep for LSM checkpoint throttle" : 0, "chunks in the LSM tree" : 0, "highest merge generation in the LSM tree" : 0, "queries that could have benefited from a Bloom filter that did not exist" : 0, "sleep for LSM merge throttle" : 0 }, "block-manager" : { "file allocation unit size" : 4096, "blocks allocated" : 7, "checkpoint size" : 12288, "allocations requiring file extension" : 7, "blocks freed" : 1, "file magic number" : 120897, "file major version number" : 1, "minor version number" : 0, "file bytes available for reuse" : 12288, "file size in bytes" : 32768 }, "btree" : { "btree checkpoint generation" : 509, "column-store variable-size deleted values" : 0, "column-store fixed-size leaf pages" : 0, "column-store internal pages" : 0, "column-store variable-size leaf pages" : 0, "pages rewritten by compaction" : 0, "number of key/value pairs" : 0, "fixed-record size" : 0, "maximum tree depth" : 3, "maximum internal page key size" : 368, "maximum internal page size" : 4096, "maximum leaf page key size" : 3276, "maximum leaf page size" : 32768, "maximum leaf page value size" : 67108864, "overflow pages" : 0, "row-store internal pages" : 0, "row-store leaf pages" : 0 }, "cache" : { "bytes read into cache" : 0, "bytes written from cache" : 342, "checkpoint blocked page eviction" : 0, "unmodified pages evicted" : 0, "page split during eviction deepened the tree" : 0, "modified pages evicted" : 0, "data source pages selected for eviction unable to be evicted" : 0, "hazard pointer blocked page eviction" : 0, "internal pages evicted" : 0, "pages split during eviction" : 0, "in-memory page splits" : 0, "overflow values cached in memory" : 0, "pages read into cache" : 0, "overflow pages read into cache" : 0, "pages written from cache" : 4 }, "compression" : { "raw compression call failed, no additional data available" : 0, "raw compression call failed, additional data available" : 0, "raw compression call succeeded" : 0, "compressed pages read" : 0, "compressed pages written" : 0, "page written failed to compress" : 0, "page written was too small to compress" : 4 }, "cursor" : { "create calls" : 3, "insert calls" : 2, "bulk-loaded cursor-insert calls" : 0, "cursor-insert key and value bytes inserted" : 103, "next calls" : 5, "prev calls" : 2, "remove calls" : 0, "cursor-remove key bytes removed" : 0, "reset calls" : 6, "search calls" : 0, "search near calls" : 0, "update calls" : 0, "cursor-update value bytes updated" : 0 }, "reconciliation" : { "dictionary matches" : 0, "internal page multi-block writes" : 0, "leaf page multi-block writes" : 0, "maximum blocks required for a page" : 0, "internal-page overflow keys" : 0, "leaf-page overflow keys" : 0, "overflow values written" : 0, "pages deleted" : 0, "page checksum matches" : 0, "page reconciliation calls" : 4, "page reconciliation calls for eviction" : 0, "leaf page key bytes discarded using prefix compression" : 0, "internal page key bytes discarded using suffix compression" : 0 }, "session" : { "object compaction" : 0, "open cursor count" : 3 }, "transaction" : { "update conflicts" : 0 } }, "nindexes" : 1, "totalIndexSize" : 32768, "indexSizes" : { "_id_" : 32768 }, "ok" : 1 }
(14)查询聚集集合总大小
> db.person.totalSize() 65536
(15)查询聚集集合存储空间大小
> db.person.storageSize() 32768
(16)查询MongoDB版本
> db.version()
3.0.9
(17)删除集合中数据
> db.person.find()
{ "_id" : ObjectId("60acfe46dac5c3b46e2b9acf"), "name" : "jack", "age" : 25 }
{ "_id" : ObjectId("60acfe88dac5c3b46e2b9ad0"), "name" : "jack2", "age" : 27 }
> db.person.remove({age:25}) #删除集合中age为25的记录
WriteResult({ "nRemoved" : 1 })
> db.person.find()
{ "_id" : ObjectId("60acfe88dac5c3b46e2b9ad0"), "name" : "jack2", "age" : 27 }
二、文档
2.1 更新文档
#Update操作查看shell中update的源码
function( query , obj , upsert , multi )
(1)upset => [update => insert]
(2)multi => 批量更新
> db.mytest.insert({"name":"gxs","age":20}) WriteResult({ "nInserted" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 20 }
2.1.1 $set
#将age为20更新为25
> db.mytest.update({"age":20},{"$set":{"age":25}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 25 }
2.1.2 $inc
Interlocked.Add:自增。
> db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 25 } > db.mytest.update({"age":25},{"$inc":{"age":10}}) #十年后 WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35 }
2.1.3 数组修改器$push
push array:增加字段。
> db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35 } > db.mytest.update({"name":"gxs"},{"$push":{"address":"beijing"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35, "address" : [ "beijing" ] } > db.mytest.update({"name":"gxs"},{"$push":{"address":"shanghai"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35, "address" : [ "beijing", "shanghai" ] }
2.1.4 数组修改器$pop
pop array:移除字段。
$pop修饰符删除数组中的第一个或者最后一个元素,给$pop传递-1会删除第一个元素传递1会删除最后一个元素
> db.mytest.update({"name":"gxs"},{"$pop":{"address":-1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35, "address" : [ "shanghai" ] }
2.1.5 $addToSet
【注】添加新文档时,拥有去重特性。
$addtoSet 和 $pop,$push 有什么区别呢?
$pop 和 $push 是把数组当成数组。
$addtoSet它把数组当成了集合。
> db.mytest.update({"age":35},{"$push":{"address":"shanghai"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35, "address" : [ "shanghai", "shanghai" ] }
【注】可以看出,$push操作新增相同字段。
> db.mytest.update({"age":35},{"$addToSet":{"address":"shanghai"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 }) > db.mytest.find() { "_id" : ObjectId("5d7c81871c5debd566331e9e"), "name" : "gxs", "age" : 35, "address" : [ "shanghai", "shanghai" ] }
【注】可以看出,$addToSet可以去重。添加新文档时,可以避免重复。
2.1.6 复合型update
【注】upsert =>update+ insert update没有找到数据,那么就会变为insert。
upsert是一种特殊的更新。要是没有文档符合更新条件,就会以这个条件和更新文档为基础创建一个新的文档。
从源码中可以看到,将find操作中的第三个参数【upsert=true】就ok了。
if (upsert) {
updateOp = updateOp.upsert();
}
> db.mytest.find() { "_id" : ObjectId("5d7e22eae2645fd39a334bec"), "name" : "gxs", "age" : 35, "address" : "shanghai" } > db.mytest.update({"name":"tom"},{"name":"mary"},true) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("5d7e23317fb18f4268a1481a") }) > db.mytest.find() { "_id" : ObjectId("5d7e22eae2645fd39a334bec"), "name" : "gxs", "age" : 35, "address" : "shanghai" } { "_id" : ObjectId("5d7e23317fb18f4268a1481a"), "name" : "mary" }
2.1.7 multi批量更新
批量更新 => update = function( query , obj , upsert , multi ) #第四个参数
multi:默认为true,判断是否批量更新的基础条件。
#源代码如下:
if (multi) {
updateOp.update(obj);
}
else {
updateOp.updateOne(obj);
}
> db.mytest.insert({"name":"mary"}) WriteResult({ "nInserted" : 1 }) > db.mytest.find() { "_id" : ObjectId("5d7e22eae2645fd39a334bec"), "name" : "gxs", "age" : 35, "address" : "shanghai" } { "_id" : ObjectId("5d7e23317fb18f4268a1481a"), "name" : "mary" } { "_id" : ObjectId("5d7e2555e2645fd39a334bed"), "name" : "mary" } > db.mytest.update({"name":"mary"},{"$set":{"name":"jackson"}},false,true) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) > db.mytest.find() { "_id" : ObjectId("5d7e22eae2645fd39a334bec"), "name" : "gxs", "age" : 35, "address" : "shanghai" } { "_id" : ObjectId("5d7e23317fb18f4268a1481a"), "name" : "jackson" } { "_id" : ObjectId("5d7e2555e2645fd39a334bed"), "name" : "jackson" }
【注】源码中,批量更新是update第4个参数,第三个是给upsert的参数。
2.1.8 更新字段
(1)添加字段
#添加address字段,设置默认值为空字符
> db.person.update({},{$set:{address:""}},{multi:true}) WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 }) > db.person.find() { "_id" : ObjectId("5d96154f61b327e54e5a872c"), "name" : "star1", "age" : 18, "address" : "" } { "_id" : ObjectId("5d96155d61b327e54e5a872d"), "name" : "star2", "age" : 17, "address" : "" } { "_id" : ObjectId("5d96156861b327e54e5a872e"), "name" : "star3", "age" : 20, "address" : "" } { "_id" : ObjectId("5d96157861b327e54e5a872f"), "name" : "star4", "age" : 19, "address" : "" } { "_id" : ObjectId("5d96157f61b327e54e5a8730"), "name" : "star5", "age" : 21, "address" : "" }
(2)更改字段
#更改address字段名为country
> db.person.update({},{$rename:{address:"country"}},{multi:true}) WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 }) > db.person.find() { "_id" : ObjectId("5d96154f61b327e54e5a872c"), "name" : "star1", "age" : 18, "country" : "" } { "_id" : ObjectId("5d96155d61b327e54e5a872d"), "name" : "star2", "age" : 17, "country" : "" } { "_id" : ObjectId("5d96156861b327e54e5a872e"), "name" : "star3", "age" : 20, "country" : "" } { "_id" : ObjectId("5d96157861b327e54e5a872f"), "name" : "star4", "age" : 19, "country" : "" } { "_id" : ObjectId("5d96157f61b327e54e5a8730"), "name" : "star5", "age" : 21, "country" : "" }
(3)删除字段
#删除country字段
> db.person.update({},{$unset:{country:""}},{multi:true}) WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 }) > db.person.find() { "_id" : ObjectId("5d96154f61b327e54e5a872c"), "name" : "star1", "age" : 18 } { "_id" : ObjectId("5d96155d61b327e54e5a872d"), "name" : "star2", "age" : 17 } { "_id" : ObjectId("5d96156861b327e54e5a872e"), "name" : "star3", "age" : 20 } { "_id" : ObjectId("5d96157861b327e54e5a872f"), "name" : "star4", "age" : 19 } { "_id" : ObjectId("5d96157f61b327e54e5a8730"), "name" : "star5", "age" : 21 }
2.1.9 save
【注】存在就更新, 不存在则插入。
if ( typeof( obj._id ) == "undefined" ){
obj._id = new ObjectId();
return this.insert( obj , opts );
}
else {
return this.update( { _id : obj._id } , obj , Object.merge({ upsert:true }, opts));
}
2.2 删除文档
2.2.1 代码逻辑
remove方法有两个参数: function( t , justOne )
if (justOne) {
removeOp.removeOne();
}
else {
removeOp.remove();
}
try {
result = bulk.execute(wc).toSingleResult();
}
2.2.2 代码演示-删除文档
> db.mytest.find() { "_id" : ObjectId("56766a124977e7f9805db203"), "name" : "jack" } { "_id" : ObjectId("56766a124977e7f9805db204"), "name" : "mary" } { "_id" : ObjectId("56766b5c4977e7f9805db205"), "name" : "jack" } > db.mytest.remove({"name":"jack"},true) #只删除一个jack > db.mytest.find() { "_id" : ObjectId("56766a124977e7f9805db204"), "name" : "mary" } { "_id" : ObjectId("56766b5c4977e7f9805db205"), "name" : "jack" } > db.mytest.insert({"name":"jack"}) > db.mytest.find() { "_id" : ObjectId("56766a124977e7f9805db204"), "name" : "mary" } { "_id" : ObjectId("56766b5c4977e7f9805db205"), "name" : "jack" } { "_id" : ObjectId("56766b994977e7f9805db206"), "name" : "jack" } > db.mytest.remove({"name":"jack"}) #删除2个jack > db.mytest.find() { "_id" : ObjectId("56766a124977e7f9805db204"), "name" : "mary" }
2.2.3 删除集合
> show dbs admin 0.000GB config 0.000GB local 0.000GB test 0.000GB > show collections mytest person > db.mytest.drop() true > show collections person
2.3 插入并保存文档
插入可以看到有三个参数 function( obj , options, _allow_dot )
可以一条一条的插入。
还可以批量插入,模式是【数组】,foreach操作。
> show dbs #查看数据库 admin 0.000GB config 0.000GB local 0.000GB test 0.000GB > show collections #查看集合 mytest person > db.mytest.find() #查看集合中的文档 { "_id" : ObjectId("5d78fce1f37ae4d4bd7e1c82"), "name" : "jack", "address" : [ "anhui", "shanghai", "beijing" ] } > db.mytest.remove({"name":"jack"}) #清空文档中数据 WriteResult({ "nRemoved" : 1 }) > db.mytest.insert([{"name":"jack"},{"name":"mary"}]) #批量插入 BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.mytest.find() { "_id" : ObjectId("5d7c58241c5debd566331e9c"), "name" : "jack" } { "_id" : ObjectId("5d7c58241c5debd566331e9d"), "name" : "mary" }
【注】好处:减少带宽量,把原来100或者1000…1w次的请求塞给mongod。如果说一次的话,tcp只有3次握手,全部搞定。
mongodb的基本单元:document文档 => Bson => mongod进程
作者:UStarGao
链接:https://www.starcto.com/mongodb/153.html
来源:STARCTO
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
UCloud云平台推荐
随便看看
- 2021-06-23 Linux性能异常经典案例分析之包量吞吐
- 2021-08-31Docker自建容器实例迁移至UCloud 容器实例Cube
- 2022-06-18MongoDB事务开发之写操作事务writeConcern
- 2021-09-2212个问题搞懂Redis
- 2022-05-12开源资产管理系统chemex容器化部署