MongoDB'S CRUD

2018-12-22  本文已影响0人  第一次真好

切换数据库,创建数据库
use stage
查看所有数据库
show dbs
创建collection

db.createCollection(collectionName, {options})
options:
    capped:true|false固定集合
    autoIndexId:true|false
    size:以字节为单位
    max:包含文档的最大文档数量,超过最大文档数以后会覆盖以前的数据

列出所有collection

show tables
show collections

插入document,如果person这个collection不存在会自动创建

db.collection.insert()
db.person.insert({"name" : "Lewis"})
db.person.insert({
  "name": "Lewis",
  "age": 26,
  "address": "Chongqing Fuling Linshi",
  "tags": ["person", "customer", "staff"]
})
db.collection.insertOne()
db.collection.insertMany([{name: "lewis"}, {name: "rose"}])

查看collection,列出所有document

db.collection.find()
db.person.find()
db.person.find().pretty()

删除collection

db.collection.drop()
db.person.drop()

更新document

db.collection.update(
    <query>,    #where
    <update>,    #set
    {
        upsert: <boolean>,    #默认更新不到数据不会插入数据
        multi: <boolean>,    #默认只更新找到的第一行
        writeConcern: <document>    #抛出异常的级别
    }
)
db.collection.save() #指定_id则更新指定数据

删除文档,不会真正释放空间

db.collection.remove(
    <query>,
    <justOne>
)
db.collection.removeOne()
db.collection.removeMany()

释放数据库空间

db.repairDatabase()
db.runCommand({repairDatabase: 1})

查找文档

db.collection.find(
    <query>,
    <projection>
)
db.collection.find({key: value})         ##等于
db.collection.find({key: {$lt: value}})  ##小于
db.collection.find({key: {$lte: value}}) ##小于或者等于
db.collection.find({key: {$gt: value}})  ##大于
db.collection.find({key: {$gte: value}}) ##大于或者等于
db.collection.find({key: {$ne: value}})  ##不等于
db.collection.find({key: value, key: value}) ##and条件
db.collection.find({$or: [{key: value}, {key: value}]})  ##or条件
db.person.find({age: {$gt: 25}, $or: [{name: "MongoDB"}, {descretion: "MongoDB教程"}]})
db.collection.find()

$type用法

db.collection.find({filed: {$type: string}})

limit()用法

db.collection.find().limit(NUMBER)
db.person.find({age: {$type: "double"}}).limit(2)

skip()用法

db.collection.find().skip(NUMBER)

sort()用法

db.collection.find().sort({KEY: 1|-1})
db.collection.find({name: "Lewis"}).sort({age: -1})

创建索引

db.collection.createIndex({KEY: options})
options:
    background Boolean:后台创建索引
    unique Boolean:唯一
    name string: 名称
    sparse Boolean: 不包含不存在该字段的文档
    ....
db.collection.getIndexes()
db.collection.totalIndexSize()
db.collection.dropIndexes()
db.collection.dropIndex("indexName")
db.collection.getIndexKeys()
db.collection.find().explain("executionStats")

聚合

db.collection.aggregate()
db.person.aggregate([{$group: {_id: "$name", total: {$sum: 1}}}])
$group: 分组 
$sum: 求和   db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg: 均值   db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min: 最小值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max: 最大值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])

$push: 将结果文档插入值到一个数组中,不保证唯一

db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])

$addToSet: 在结果文档中插入值到一个数组中,但不创建副本,保证唯一

  db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
  dn.person.update({"favorites.movies": "Casablanca"}, {$addToSet: {"favorites.movies": "The Maltese Falcon"}}, false, true)

$first: 根据文档的排序获取第一个

db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])

$last: 根据文档的排序获取最后一个

db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

管道

管道 说明
$project 修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
$match 用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
$limit 用来限制MongoDB聚合管道返回的文档数。
$skip 在聚合管道中跳过指定数量的文档,并返回余下的文档。
$unwind 将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
$group 将集合中的文档分组,可用于统计结果。
$sort 将输入文档排序后输出。
$geoNear 输出接近某一地理位置的有序文档。

查看数据库或者表状态

db.stats()
db.collection.stats()

集合操作符

运算符 描述
$in 如果任意参数在引用集合里,则匹配
$all 如果所有参数在引用集合里且被使用在包含数组的文档中,则匹配
$nin 如果没有参数在引用的文档里,则匹配
products = db.products.findOne({salecnt: {$gt: 100}})
db.products.find(products.['_id']: {$in: [ObjectId("5bf8c9bd2d30916367372384"),ObjectId("5bf8ca642d30916367372386")]})
db.products.find({'details.color': {$nin: ["green", "black"]}})
db.products.find({'tags': {'$in': ["gift", "garden"]}})

范围运算符

运算符 描述
$lt 小于
$gt 大于
$lte 小于等于
$gte 大于等于

布尔运算符

运算符 描述
$ne 不匹配参数条件
$not 不匹配结果
$or 有一个条件匹配就成立
$nor 所有条件都不匹配
$and 所有条件都匹配
$exists 判断元素是否存在

数组运算符

运算符 描述
$elemMatch 如果提供的所有词语在相同子文档中,则匹配
$size 如果子文档数组大小与提供的文本值相同,则匹配
上一篇 下一篇

猜你喜欢

热点阅读