MongoDB常用操作

时间:2019-10-19 14:45:17   收藏:0   阅读:82

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

EDITOR="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\""

use docname
show dbs
db.docname.insert({key:value,key:value,...})
show collections
db.docname
db.colname.find()
db.colname.findOne()
db.colname.update({key:value},{$set:{key:value,...}})
db.colname.drop()
db.dropDatabases()
db.stats()
db.help()

直接执行function insert(object){db.getCollection("colname").insert(objection)}

调用insert({key:value,...})

修改器指定一个键值对,存在键就修改,不存在就创建

$set{$set:{field:value}}

\(inc{\)inc:{field:value}}

\(unset{\)set:{field:1}}

\(push{\)push:{field:value}}

\(pushAll{\)pushAll:{field:array}}

\(addToSet{\)addToSet:{field:value}}

\(pull{\)pull{field:value}}

\(pullAll{\)pullAll{field:array}}

{ "_id" : 4, "books" : [ { "type" : "js", "name" : "extjs4" }, { "type" : "js", "name" : "jquery" }, { "type" : "db", "name" : "mongodb" } ] }

db.student.update({"books.type":"js"},{\(set:{"books.\).count":152}})

db.colname.remove({field:value})

$addToSet与$each结合批量数组更新

db.colname.update({field:value},{$addToSet:{field:{$each:[value,...]}}})

runCommand可以执行MongoDB中的特殊函数

findAndModify(特殊函数)返回update或remove后的文档

runCommand({"findAndModify":"processes",query:{查询器},sort{排序},new:trueupdate:{更新器},remove:true})

EG:ps = db.runCommand({findAndModify:"student",query:{name:"maxkim"},update:{$set:{age:234}},new:true})

ps.value
db.colname.find({field:{$...:...}},{_id:0, name:1,...})

$gte 大于等于

$gt 大于

$lte 小于等于

$lt 小于

$in 任意参数在引用集合里,则匹配

db.c2.find({age:{$in:[1,2,3]}})
db.c2.find({$or:[{age:{$lt:5}},{age:{$gt:999995}}]})
db.product.find({},{reviews:{$slice:12}}) 
db.product.find({},{reviews:{$slice:-5}}) 

正则查询

db.colname.find({field:/li/i},{field:0,...})

db.review.find({text:/best|worst/i})

db.review.find({text:{$regex:"best|worsst",$options:"i"}})
db.colname.find({field.n:value})$size 
db.persons.find({books:{$size:4}},{_id:0, books:1})
db.persons.update({},{$set:{field:n}},false,true)
db.persons.update({},{$push:{field:"value"},$inc:{field:1}})
db.books.ensureIndex({number:1})
db.books.ensureIndex({name:1},{name:"new_name"})
db.books.ensureIndex({name:-1},{unique:true})
db.books.ensureIndex({name:-1},{unique:true,dropDups:true})
db.books.find({name:"",number:1}).hint({name:-1})
db.books.find({name:"",number:1}).explain
db.runCommand({dropIndexes:"books", index:"name_1"})
db.runCommand({dropIndexes:"books", index:"*"})
db.users.find({'addresses.name':"home"}).pretty()

$elemMatch 
db.users.find({addresses:{$elemMatch:{name:"home",state:"NY"}}})
db.users.find({address:{$size:3}})
db.reviews.find({$where:"this.helpful_votes>3"})

2D查询数据

var map = [{ "gis" : { "x" : 185, "y" : 150 }},{ "gis" : { "x" : 70, "y" : 180 }},{ "gis" : { "x" : 75, "y" : 180 }},{ "gis" : { "x" : 185, "y" : 185 }},{ "gis" : { "x" : 65, "y" : 185 }},{ "gis" : { "x" : 50, "y" : 50 }},{ "gis" : { "x" : 50, "y" : 50 }},{ "gis" : { "x" : 60, "y" : 55 }},{ "gis" : { "x" : 65, "y" : 80 }},{ "gis" : { "x" : 55, "y" : 80 }},{ "gis" : { "x" : 0, "y" : 0 }},{ "gis" : { "x" : 0, "y" : 200 }},{ "gis" : { "x" : 200, "y" : 0 }},{ "gis" : { "x" : 200, "y" : 200 }}]for(var i = 0;iprev.m){
prev.m = doc.m;
prev.name = doc.name;
prev.country = doc.country;
}
},
condition:{m:{$gt:90}} }}
)
db.createCollection("MyColl",{size:1000,capped:true,max:10})
db.runCommand({convertToCapped:"persons",size:100000})
db.MyColl.find().sort({$natural:-1})

GridFS

mongofiles -d colname -l "localfile" put "filename"
mongofiles -d test list
mongofiles -d test delete 'filename'
db.eval("function(name){return name;}","uspcat")
mongoexport.exe -d test -c persons -o "D:\MongoDB\log\dump.json"
mongoimport.exe --db test --collection persons --file "D:\MongoDB\log\dump.json"
mongodump.exe --host 127.0.0.1:27017 -d test -o "D:\MongoDB\log\test"
mongorestore.exe --host 127.0.0.1:27017 -d test "D:\MongoDB\log\test.json\test\"

fsync
db.runCommand({fsync:1, lock:1})
db.currentOp()
db.repairDatabase()
 db.createUser({user:"pangdahai",pwd:"123",roles:
[{role:"readWriteAnyDatabase",db:"admin"}]})
Successfully added user: {
        "user" : "quanee",
        "roles" : [
                {
                        "role" : "readWriteAnyDatabase",
                        "db" : "admin"
                }
        ]
}
db.auth("username","password")
db.system.users.remove({user:"username"})
db.system.users.find()

mongo 127.0.0.1:27017/username

主从复制

master.conf

dbpath=D:\MongoDB\master

port = 8888

bind_ip = 127.0.0.1

master=true
dbpath=D:\MongoDB\slave

port = 7777

bind_ip = 127.0.0.1

source = 127.0.0.1:8888 #主服务器数据源

slave = true
db.getMongo().setSlaveOk();
(rs.setSlaveOk())
db.values.reIndex()
db.setProfilingLevel(2)
hing({indexname:1})

$** 匹配任意字段中包含的字符串

-- 解析字符串>>>删除分词>>>匹配词干

-- 关键字使用双引号包含,必须匹配含有双引号的短语

db.books.find({$text:{$search:'"books"'}})  匹配含有books的短语
db.books.find({$text:{$search:'mongodb -second'}}) 搜索匹配mongodb但不包含second的短语
db.books.find({$text:{$search:'mongodb -"second"  '}}) 搜索匹配mongodb但不包含second的文档
db.books.createIndex(
{'$**': 'text'},<--使用字符串索引索引所有字段
{weights:
{title: 10, <---为字段指定1以外的权重
dategories:5}
}
)
db.books.createIndex(
{'$**':'text'},
{weights:
{title:10,
categories:5},
name:'index_name',
default_language:'french'
}
)

切换存储引擎到WiredTiger

storage:
dbpath:"/data/db"   数据库存储路径
joural:
enabled:true    是否启用日志,默认true
engine:"wiredTiger" 存储引擎,默认mmapv1
wiredTiger:
engineConfig:
cacheSizeGB:8   使用内存大小,默认是物理内存的一半,至少1G
journalCompressor:none  日志压缩器,默认snappy, 设置为none获取最佳性能
collectionConfig:
blockCompressor:none    集合数据压缩器(none,snappy,zlib)
indexConfig:
prefixCompression:false 是否为索引使用压缩
collection.aggregate(pipeline)
pipline=[{$match:?},
{$group:?},
{$sort:?},
{$limit:?},
{$skip:?},
{$unwind:?},
{$redact:?},
{$sample:?},
{$out:?}
]
pipeline = [
{'$match':{'$and':[{'pub_date':'2016.12.24'},{'time':3}]}},
{'$group':{'_id':'$price','counts':{'$sum':1}}},
{'$sort' :{'counts':-1}},
{'$limit':10}
]
pipeline2 = [
{'$match':{'$and':[{'pub_date':'2015.12.24'},{'time':3}]}},
{'$group':{'_id':{'$slice':['$cates',2,1]},'counts':{'$sum':1}}},
{'$sort':{'counts':-1}}
]
item_info.aggregate(pipeline)
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!