MongoDB操作简记

一、数据库操作

1.显示当前选择的数据库

[root@weekend05 ~]# mongod --dbpath /data/db/

[root@weekend05 ~]# mongo

MongoDB shell version: 3.2.6

connecting to: test

。。。。

> db

test

2.创建或切换数据库MyDB

> use MyDB

switched to db MyDB

> db

MyDB

3.查看所有数据库

> show dbs

local 0.000GB

4.向MyDB插入一个文件

5.查看所有数据库

> db.movie.insert({"name":"tutorials yiibai"})

WriteResult({ "nInserted" : 1 })

> show dbs

MyDB 0.000GB

local 0.000GB

6.删除数据库MyDB

> db.dropDatabase()

{ "dropped" : "MyDB", "ok" : 1 }

二、集合操作

1.显式和隐式创建集合movie

显示创建

> db.createCollection("movie")

{ "ok" : 1 }

隐式创建

> db.movie.insert({"name":"tutorials yiibai"})

WriteResult({ "nInserted" : 1 })

2.查询所有集合

> show collections

movie

> db.getCollectionNames();

[ "movie" ]

3.查看集合总数据量

> db.movie.count();

1

4.查看movie集合所在数据库

> db.movie.getDB();

MyDB

5.查看当前集合movie状态

db.movie.stats();

{

"ns" : "MyDB.movie",

"count" : 1,

"size" : 49,

"avgObjSize" : 49,

"storageSize" : 16384,

"capped" : false,

"wiredTiger" : {

"metadata" : {

"formatVersion" : 1

},

"creationString" : "allocation_size=4KB,app_metadata=(formatVersion=1),block_allocation=best,block_compressor=snappy,cache_resident=0,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=0,extractor=,format=btree,huffman_key=,huffman_value=,immutable=0,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,log=(enabled=),lsm=(auto_throttle=,bloom=,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=0,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_max=15,merge_min=0),memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=0,prefix_compression_min=4,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,type=file,value_format=u",

"type" : "file",

"uri" : "statistics:table:collection-2-2834400305576058642",

"LSM" : {

"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,

"bloom filters in the LSM tree" : 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 checkpoint throttle" : 0,

"sleep for LSM merge throttle" : 0,

"total size of bloom filters" : 0

},

"block-manager" : {

"allocations requiring file extension" : 3,

"blocks allocated" : 3,

"blocks freed" : 0,

"checkpoint size" : 8192,

"file allocation unit size" : 4096,

"file bytes available for reuse" : 0,

"file magic number" : 120897,

"file major version number" : 1,

"file size in bytes" : 16384,

"minor version number" : 0

},

"btree" : {

"btree checkpoint generation" : 7,

"column-store fixed-size leaf pages" : 0,

"column-store internal pages" : 0,

"column-store variable-size RLE encoded values" : 0,

"column-store variable-size deleted values" : 0,

"column-store variable-size leaf pages" : 0,

"fixed-record size" : 0,

"maximum internal page key size" : 368,

"maximum internal page size" : 4096,

"maximum leaf page key size" : 2867,

"maximum leaf page size" : 32768,

"maximum leaf page value size" : 67108864,

"maximum tree depth" : 3,

"number of key/value pairs" : 0,

"overflow pages" : 0,

"pages rewritten by compaction" : 0,

"row-store internal pages" : 0,

"row-store leaf pages" : 0

},

"cache" : {

"bytes read into cache" : 0,

"bytes written from cache" : 143,

"checkpoint blocked page eviction" : 0,

"data source pages selected for eviction unable to be evicted" : 0,

"hazard pointer blocked page eviction" : 0,

"in-memory page passed criteria to be split" : 0,

"in-memory page splits" : 0,

"internal pages evicted" : 0,

"internal pages split during eviction" : 0,

"leaf pages split during eviction" : 0,

"modified pages evicted" : 0,

"overflow pages read into cache" : 0,

"overflow values cached in memory" : 0,

"page split during eviction deepened the tree" : 0,

"page written requiring lookaside records" : 0,

"pages read into cache" : 0,

"pages read into cache requiring lookaside entries" : 0,

"pages written from cache" : 2,

"pages written requiring in-memory restoration" : 0,

"unmodified pages evicted" : 0

},

"compression" : {

"compressed pages read" : 0,

"compressed pages written" : 0,

"page written failed to compress" : 0,

"page written was too small to compress" : 2,

"raw compression call failed, additional data available" : 0,

"raw compression call failed, no additional data available" : 0,

"raw compression call succeeded" : 0

},

"cursor" : {

"bulk-loaded cursor-insert calls" : 0,

"create calls" : 1,

"cursor-insert key and value bytes inserted" : 50,

"cursor-remove key bytes removed" : 0,

"cursor-update value bytes updated" : 0,

"insert calls" : 1,

"next calls" : 0,

"prev calls" : 1,

"remove calls" : 0,

"reset calls" : 2,

"restarted searches" : 0,

"search calls" : 0,

"search near calls" : 0,

"truncate calls" : 0,

"update calls" : 0

},

"reconciliation" : {

"dictionary matches" : 0,

"fast-path pages deleted" : 0,

"internal page key bytes discarded using suffix compression" : 0,

"internal page multi-block writes" : 0,

"internal-page overflow keys" : 0,

"leaf page key bytes discarded using prefix compression" : 0,

"leaf page multi-block writes" : 0,

"leaf-page overflow keys" : 0,

"maximum blocks required for a page" : 0,

"overflow values written" : 0,

"page checksum matches" : 0,

"page reconciliation calls" : 2,

"page reconciliation calls for eviction" : 0,

"pages deleted" : 0

},

"session" : {

"object compaction" : 0,

"open cursor count" : 1

},

"transaction" : {

"update conflicts" : 0

}

},

"nindexes" : 1,

"totalIndexSize" : 16384,

"indexSizes" : {

"_id_" : 16384

},

"ok" : 1

}

>

6.集合movie重命名

> db.movie.renameCollection("movies");

{ "ok" : 1 }

7.集合movie复制

> db.movies.copyTo("movie")

WARNING: db.eval is deprecated

1

8.删除集合movie

> db.movies.drop();

true

9.查看集合movie帮助

> db.movie.help();

DBCollection help

db.movie.find().help() - show DBCursor help

。。。下面内容太多省略

三、文档操作

1.插入操作

a.单个插入

> db.movie.insert({"name":"HuanLeSong","Times":10000})

WriteResult({ "nInserted" : 1 })

> db.movie.insert({"name":"SanJie","Times":20000})

WriteResult({ "nInserted" : 1 })

> db.movie.insert({"name":"SanJie","Address":"China"})

WriteResult({ "nInserted" : 1 })

> db.movie.find()

{ "_id" : ObjectId("5752948a6655ed3d2695cc1d"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("575295dd6655ed3d2695cc1e"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("575295ee6655ed3d2695cc1f"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("575296006655ed3d2695cc20"), "name" : "SanJie", "Address" : "China" }

创建文档变量,对象

> movieVar1 = {"name":"HuanLeSong","Times":10000};

{ "name" : "HuanLeSong", "Times" : 10000 }

> movieVar2 = {"name":"SanJie","Times":20000};

{ "name" : "SanJie", "Times" : 20000 }

> movieVar3 = {"name":"SanJie","Address":"China"};

{ "name" : "SanJie", "Address" : "China" }

> db.movie.insert(movieVar1)

WriteResult({ "nInserted" : 1 })

> db.movie.insert(movieVar2)

WriteResult({ "nInserted" : 1 })

> db.movie.insert(movieVar3)

WriteResult({ "nInserted" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e52d8cfe9d7161059ed50"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e550dcfe9d7161059ed51"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e5517cfe9d7161059ed52"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e551acfe9d7161059ed53"), "name" : "SanJie", "Address" : "China" }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed54"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed55"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed56"), "name" : "SanJie", "Address" : "China" }

> db.movie.insert({"_id":08001,"name":"zhangsan"})

WriteResult({ "nInserted" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e52d8cfe9d7161059ed50"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e550dcfe9d7161059ed51"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e5517cfe9d7161059ed52"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e551acfe9d7161059ed53"), "name" : "SanJie", "Address" : "China" }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed54"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed55"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed56"), "name" : "SanJie", "Address" : "China" }

{ "_id" : 8001, "name" : "zhangsan" }db.movie.insert({"_id":08001,"name":"lisi"})

db.movie.save({"_id":08001,"name":"lisi"})

db.movie.find()

> db.movie.insert({"_id":08001,"name":"lisi"})

WriteResult({

"nInserted" : 0,

"writeError" : {

"code" : 11000,

"errmsg" : "E11000 duplicate key error collection: mydb.movie index: _id_ dup key: { : 8001.0 }"

}

})

> db.movie.save({"_id":08001,"name":"lisi"})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e52d8cfe9d7161059ed50"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e550dcfe9d7161059ed51"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e5517cfe9d7161059ed52"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e551acfe9d7161059ed53"), "name" : "SanJie", "Address" : "China" }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed54"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed55"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("574e55a0cfe9d7161059ed56"), "name" : "SanJie", "Address" : "China" }

{ "_id" : 8001, "name" : "lisi" }

>

综上结果可知:

Insert和Save的区别是:如果插入的集合的“_id”值,在集合中已经存在,用Insert执行插入操作回报异常,已经存在"_id"的键。用Save如果系统中没有相同的"_id"就执行插入操作,有的话就执行覆盖掉原来的值。相当于修改操作。

b.批量插入

采用数组的方式 []

> db.movie.insert([{username:'aaa',password:'bbb',tel:'123123123'},{username:'bbb',password:'ccc',tel:'123123234'}]);

BulkWriteResult({

"writeErrors" : [ ],

"writeConcernErrors" : [ ],

"nInserted" : 2,

"nUpserted" : 0,

"nMatched" : 0,

"nModified" : 0,

"nRemoved" : 0,

"upserted" : [ ]

})

> db.movie.find()

{ "_id" : ObjectId("5752948a6655ed3d2695cc1d"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("575295dd6655ed3d2695cc1e"), "name" : "HuanLeSong", "Times" : 10000 }

{ "_id" : ObjectId("575295ee6655ed3d2695cc1f"), "name" : "SanJie", "Times" : 20000 }

{ "_id" : ObjectId("575296006655ed3d2695cc20"), "name" : "SanJie", "Address" : "China" }

{ "_id" : ObjectId("575296c26655ed3d2695cc21"), "username" : "aaa", "password" : "bbb", "tel" : "123123123" }

{ "_id" : ObjectId("575296c26655ed3d2695cc22"), "username" : "bbb", "password" : "ccc", "tel" : "123123234" }

2.删除操作

1)按条件删除

> db.movie.remove({"name":"HuanLeSong"})

WriteResult({ "nRemoved" : 2 })

2)删除所有

> db.movie.remove({})

WriteResult({ "nRemoved" : 8 })

> db.movie.find()

> show collections

Movie

由上述结果得出remove({})和drop()的区别:

remove({}):删除所有文档,但不会删除集合本身,原索引也会保留

drop():删除整个集合,包括索引,然后重新创建集合和建立索引

3.修改操作

文档存入数据库后,就可以用update方法来修改它,update有两个参数一个是查询文档,找出需要更新的文档。一个是修改文档,描述对找到的文档做哪些修改

更新操作是原子的,若是两个更新同时发生,先到达服务器的先执行。

a.替换更新update

> db.movie.update({username:"bbb"},{password:"abc"});

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

b.修改器更新

I.$set修改器

$set用来指定一个键的值,如果这个键不存在,就创建它。并且,只修改第一个

> db.movie.update({username:"aaa"},{$set:{password:"*****"}});

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

II.$unset修改器

$unset来删除一个键

> db.movie.update({username:"aaa"},{$unset:{tel:1}});

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

III.$inc修改器

$inc用来增加已有的键值,或者在键值不存在时创建。

> db.movie.update({username:"aaa"},{$inc:{age:2}}); --键值age不存在,创建age并赋值2

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

IV.upsert

当update的第三个参数设置为true的时候,为upsert模式

upsert是一个特殊的更新。当没有文档符合更新条件,就会以这个条件创建新的文档。

> db.movie.update({username:'aaa'},{$inc:{age:2}});--当没有文档符合更新条件,就会以这个条件创建新的文档

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

> db.movie.update({username:'aaa'},{$set:{abc:123}},true)

WriteResult({

"nMatched" : 0,

"nUpserted" : 1,

"nModified" : 0,

"_id" : ObjectId("574e5a67c7c9984dce48a02a")

})

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 123 }

> db.movie.update({username:'aaa'},{$set:{abc:234}},true) --当文档符合更新条件,就会更新文档

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234 }

V.数组修改器

数组修改器只能用于数组。[]

$push会像已有的数组末尾假如一个元素

$pop会从头部删除一个元素

> db.movie.update({username:'aaa'},{$push:{arr:1}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 1 ] }

> db.movie.update({username:'aaa'},{$push:{arr:2}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 1, 2 ] }

> db.movie.update({username:'aaa'},{$push:{arr:5}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 1, 2, 5 ] }

> db.movie.update({username:'aaa'},{$push:{arr:3}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 1, 2, 5, 3 ] }

> db.movie.update({username:'aaa'},{$pop:{arr:1}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 1, 2, 5 ] }

> db.movie.update({username:'aaa'},{$pop:{arr:-1}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 2, 5 ] }

VI.数组的定位修改器

若是数组中多个值,我们只想修改其中的部分值,有两种方法操作数组中的值:通过位置和定位操作符($)

数组下标是从0开始

db.movie.update({username:'aaa'},{$set:{'arr.2':10}});

db.movie.find()

> db.movie.update({username:'aaa'},{$set:{'arr.2':10}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 2, 5, 10 ] }

> db.movie.update({'arr.2':10},{$set:{'arr.$':100}});

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 2, 5, 100 ] }

VII.多文档修改

第四个参数设置为true

> db.movie.insert([{username:'aaa',password:'bbb',tel:'123123123'},{username:'bbb',password:'ccc',tel:'123123234'}]);

BulkWriteResult({

"writeErrors" : [ ],

"writeConcernErrors" : [ ],

"nInserted" : 2,

"nUpserted" : 0,

"nMatched" : 0,

"nModified" : 0,

"nRemoved" : 0,

"upserted" : [ ]

})

>

> db.movie.update({username:"aaa"},{$set:{password:"******"}},false,true);

WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

> db.movie.find()

{ "_id" : ObjectId("574e58aecfe9d7161059ed59"), "name" : "tutorials yiibai" }

{ "_id" : ObjectId("574e5a67c7c9984dce48a02a"), "username" : "aaa", "abc" : 234, "arr" : [ 2, 5, 100 ], "password" : "******" }

{ "_id" : ObjectId("574e73d1cfe9d7161059ed5a"), "username" : "aaa", "password" : "******", "tel" : "123123123" }

{ "_id" : ObjectId("574e73d1cfe9d7161059ed5b"), "username" : "bbb", "password" : "ccc", "tel" : "123123234" }

原文地址:https://www.cnblogs.com/zd520pyx1314/p/7246593.html