MongoDB数据库实例建立后,就可以对数据库进行各种操作了,比如插入,更新,删除,查询,索引,聚合,复制,分片等等
1、插入文档
2、查询文档
3、更新文档
4、删除文档
MongoDB集合的文档记录,若不需要,可以通过命令永久删除
语法:db.collection.remove
(
<query>,//删除文档条件
{
justOne:<boolean>,
writeConcern:<document>,
collation:<document>
}
)
命令说明:
在集合里删除一条或者多条的文档
参数说明:
query:必须,设置文档删除条件
justOne:可选,false为默认值,删除符合条件的所有文档;true删除符合条件的一条文档
writeConcern:可选;自定义写出错确认级别
collation:可选;指定特定国家语言的更新归类规则
返回值:
删除成功,返回WriteResult({ "nRemoved" : 1 })
删除失败,返回结果中会包含WriteResult.writeConcernError对象字段内容
实例:
删除集合里的所有文档
> db.test1.insertMany(
... [
... {item:"铅笔",price:2},
... {item:"钢笔",price:20},
... {item:"毛笔",price:15}
... ]
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5b3480fd5ae81fb5335bcebb"),
ObjectId("5b3480fd5ae81fb5335bcebc"),
ObjectId("5b3480fd5ae81fb5335bcebd")
]
}
> db.test1.find().pretty()
{ "_id" :ObjectId("5b3480fd5ae81fb5335bcebb"), "item" : "铅笔","price" : 2 }
{
"_id" : ObjectId("5b3480fd5ae81fb5335bcebc"),
"item" : "钢笔",
"price" : 20
}
{
"_id" : ObjectId("5b3480fd5ae81fb5335bcebd"),
"item" : "毛笔",
"price" : 15
}
>
>
> db.test1.remove() //这样就是没有删除的条件
2018-06-28T14:32:44.371+0800 E QUERY [thread1] Error: remove needs a query :
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:357:1
DBCollection.prototype.remove@src/mongo/shell/collection.js:382:18
@(shell):1:1
> db.test1.remove({}) //{}就是删除的条件
WriteResult({ "nRemoved" : 3 })
>
删除符合条件的所有文档记录
> db.test1.insertMany(
... [
... {item:"铅笔",price:2},
... {item:"钢笔",price:20},
... {item:"毛笔",price:15}
... ]
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5b3481d75ae81fb5335bcebe"),
ObjectId("5b3481d75ae81fb5335bcebf"),
ObjectId("5b3481d75ae81fb5335bcec0")
]
}
>
> db.test1.find().pretty()
{ "_id" :ObjectId("5b3481d75ae81fb5335bcebe"), "item" : "铅笔","price" : 2 }
{
"_id" : ObjectId("5b3481d75ae81fb5335bcebf"),
"item" : "钢笔",
"price" : 20
}
{
"_id" : ObjectId("5b3481d75ae81fb5335bcec0"),
"item" : "毛笔",
"price" : 15
}
>
>
>
> db.test1.remove({price:{$gt:10}}) //删除商品价格大于10的文档记录
WriteResult({ "nRemoved" : 2 })
> db.test1.find().pretty()
{ "_id" :ObjectId("5b3481d75ae81fb5335bcebe"), "item" : "铅笔","price" : 2 }
>
自定义写出错确认级别
writeConcern选项为update修改数据异常时,提供出错处理机制
db.order.update(
{
price:{$lt:3}
},
writeConcern:{w:"majority",wtimeout:5000} //删除价格小于3的所有文档记录,超时5秒中断操作,返回该命令的操作记录
}
)
删除满足条件的单个文档记录
> db.test1.insertMany(
... [
... {item:"铅笔",price:2},
... {item:"钢笔",price:20},
... {item:"毛笔",price:15}
... ]
... )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5b3485225ae81fb5335bceca"),
ObjectId("5b3485225ae81fb5335bcecb"),
ObjectId("5b3485225ae81fb5335bcecc")
]
}
>
> db.test1.find().pretty()
{ "_id" : ObjectId("5b3485225ae81fb5335bceca"),"item" : "铅笔", "price" : 2 }
{
"_id" : ObjectId("5b3485225ae81fb5335bcecb"),
"item" : "钢笔",
"price" : 20
}
{
"_id" : ObjectId("5b3485225ae81fb5335bcecc"),
"item" : "毛笔",
"price" : 15
}
> db.test1.remove({
... price:{$gte:3}
... },
... {
... justOne:true //删除价格大于3的第一条文档
... }
... )
WriteResult({ "nRemoved" : 1 })
>
> db.test1.find().pretty()
{ "_id" :ObjectId("5b3485225ae81fb5335bceca"), "item" : "铅笔","price" : 2 }
{
"_id" : ObjectId("5b3485225ae81fb5335bcecc"),
"item" : "毛笔",
"price" : 15
}
>
5、索引
MongoDB是基于集合建立索引(index),索引的作用类似于传统数据库,目的是为了提高查询速度。没有索引,会做全集合扫描,建立了索引,会扫描索引内容。创建索引会增加额外的存储空间开销;在已创建索引的集合里,新增集合文档的话,则会引起索引重新排序,这个过程影响查询速度。MongoDB的索引基于B-tree数据结构和算法形成。
默认情况下,在建立集合的同时,MongoDB数据库自动为集合_id建立唯一索引,可以避免_id值重复。
单一字段(key)索引
语法:db.collection.createIndex({<key>:<n>})
命令说明:对一个集合文档的键建立索引,key为键名,n=1为升序,n=-1为降序
> db.books.insert(
... [
... {name:"《故事汇》",price:20,color:"red"},
... {name:"《读者》",price:45,color:"white"},
... {name:"《儿童历史》",price:120,color:"green"},
... {name:"《世界地理》",price:20,color:"yellow"}
... ]
... )
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 4,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.books.createIndex(
... {name:1}
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.books.find(
... {name:{$regex:/历史》$/}},
... {_id:0}
... ).pretty()
{ "name" : "《儿童历史》","price" : 120, "color" : "green" }
>
嵌套文档单字段索引
> db.books.insert(
... [
... {name:"《故事汇》",price:20,color:"red",tags:{press:"清华大学出版社",call:"1
3600000000"}},
... {name:"《读者》",price:45,color:"white",tags:{press:"人民文学出版社",call:"1
3700000000"}},
... {name:"《儿童历史》",price:120,color:"green",tags:{press:"线装书局",call:"13
800000000"}},
... {name:"《世界地理》",price:20,color:"yellow",tags:{press:"燕山出版社",call:"
13900000000"}}
... ]
... )
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 4,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
> db.books.createIndex(
... {"tags.press":1}
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
> db.books.find(
... {"tags.press":{$regex:/出版社$/}},
... {_id:0}
... ).pretty()
{
"name" : "《读者》",
"price" : 45,
"color" : "white",
"tags" : {
"press" : "人民文学出版社",
"call" : "13700000000"
}
}
{
"name" : "《故事汇》",
"price" : 20,
"color" : "red",
"tags" : {
"press" : "清华大学出版社",
"call" : "13600000000"
}
}
{
"name" : "《世界地理》",
"price" : 20,
"color" : "yellow",
"tags" : {
"press" : "燕山出版社",
"call" : "13900000000"
}
}
>
字段值唯一索引
语法:db.collection.createIndex({<key>:<n>,<key>:<n>,<key>:<n>,...},{unique:true})
命令说明:对一个或多个字段建立唯一索引。key为键名,n=1为升序,n=-1为降序
> db.books.createIndex( {name:1},{unique:true} )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
首先这个字段上不能已经存在单一索引,否则会报错:
> db.books.createIndex(
... {name:1},{unique:true}
... )
{
"ok" : 0,
"errmsg" : "Index with name: name_1 already exists withdifferent option
s",
"code" : 85,
"codeName" : "IndexOptionsConflict"
}
再者,name的值必须唯一,不能重复,否则MongoDB将新插入的重复文档予以拒绝。
多字段索引
语法:db.collection.createIndex({<key>:<n>,<key>:<n>,<key>:<n>,...})
命令说明:对两个或多个字段建立唯一索引。key为键名,n=1为升序,n=-1为降序
> db.books.createIndex(
... {price:1,color:-1}
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}
> db.books.find(
... {},
... {_id:0}
... ).sort({price:1,color:-1}).pretty() //用sort排序查询
{
"name" : "《世界地理》",
"price" : 20,
"color" : "yellow",
"tags" : {
"press" : "燕山出版社",
"call" : "13900000000"
}
}
{
"name" : "《故事汇》",
"price" : 20,
"color" : "red",
"tags" : {
"press" : "清华大学出版社",
"call" : "13600000000"
}
}
{
"name" : "《读者》",
"price" : 45,
"color" : "white",
"tags" : {
"press" : "人民文学出版社",
"call" : "13700000000"
}
}
{
"name" : "《儿童历史》",
"price" : 120,
"color" : "green",
"tags" : {
"press" : "线装书局",
"call" : "13800000000"
}
}
>
查询的结果先做price生序排序,值一样的情况,再做color降序排序。
多字段唯一索引
语法:db.collection.createIndex({<key>:<n>,<key>:<n>,<key>:<n>,...},{unique:true})
命令说明:对两个或多个字段建立唯一索引。key为键名,n=1为升序,n=-1为降序
文本索引
语法:db.collection.createIndex({<key1>:"text",<key2>:"text",...})
命令说明:在集合里,为文本字段内容的文档建立文本索引
基本文档索引
db.books.find(
{name:{$regex:/历史》$/}},
{_id:0}
).pretty()
制定权重文本索引
> db.books.createIndex(
... {
... name:"text",
... price:"text"
... },
... {
... weights:{name:10},
... name:"TextIndex"
... }
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
注意:相关字段上不能存在文本索引,否则会报错:
> db.books.createIndex(
... {
... name:"text",
... price:"text"
... },
... {
... weights:{name:10},
... name:"TextIndex"
... }
... )
{
"ok" : 0,
"errmsg" : "Index: { v: 2, key: { _fts:\"text\", _ftsx: 1 }, name: \"Te
xtIndex\", ns: \"goodsdb.books\",weights: { name: 10, price: 1 }, default_langu
age: \"english\", language_override:\"language\", textIndexVersion: 3 } already
exists withdifferent options: { v: 2, key: { _fts: \"text\", _ftsx: 1 }, name:
\"name_text\", ns:\"goodsdb.books\", weights: { name: 1 }, default_language: \
"english\", language_override:\"language\", textIndexVersion: 3 }",
"code" : 85,
"codeName" : "IndexOptionsConflict"
}
通配符文本索引
为指定集合里的所有字符串内容进行搜索提供通配索引
> db.books.createIndex(
... {"$**":"text"}
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
注意:相关字段上不能存在文本索引,否则会报错:同上。
哈希索引
用于支持对分片键(带hash键值对的分片集合)的分片数据索引,主要用于分布式数据索引。
语法:db.collection.createIndex({<key>:"hashed"})
命令说明:key为含hash值的键
> db.books.createIndex(
... {_id:"hashed"}
... )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
注意,hashed不支持多字段索引;hashed会把浮点数的小数部分自动去掉;hashed不支持唯一索引。
和索引相关的其他方法:
db.books.dropIndex(index):移除索引功能,可以指定索引名
db.books.dropIndexes():移除集合下的所有索引
db.books.getIndexes():返回一个集合现有索引描述信息的文档数组
db.books.reIndex():删除所有索引并重构现有索引
db.books.totalIndexSize():统计集合索引的大小信息




