Mongodb数据库操作

 mysql/mongodb对比

CREATE TABLE USERS (a Number, b Number)
Implicit or use MongoDB::createCollection().
INSERT INTO USERS VALUES(1,1)
$db->users->insert(array("a" => 1, "b" => 1));
SELECT a,b FROM users
$db->users->find(array(), array("a" => 1, "b" => 1));
SELECT * FROM users WHERE age=33
$db->users->find(array("age" => 33));
SELECT a,b FROM users WHERE age=33
$db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
SELECT a,b FROM users WHERE age=33
$db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
SELECT a,b FROM users WHERE age=33 ORDER BY name
$db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1));
SELECT * FROM users WHERE age>33
$db->users->find(array("age" => array('$gt' => 33)));
SELECT * FROM users WHERE age<33
$db->users->find(array("age" => array('$lt' => 33)));
SELECT * FROM users WHERE name LIKE "%Joe%"
$db->users->find(array("name" => new MongoRegex("/Joe/")));
SELECT * FROM users WHERE name LIKE "Joe%"
$db->users->find(array("name" => new MongoRegex("/^Joe/")));
SELECT * FROM users WHERE age>33 AND age<=40
$db->users->find(array("age" => array('$gt' => 33, '$lte' => 40)));
SELECT * FROM users ORDER BY name DESC
$db->users->find()->sort(array("name" => -1));
CREATE INDEX myindexname ON users(name)
$db->users->ensureIndex(array("name" => 1));
CREATE INDEX myindexname ON users(name,ts DESC)
$db->users->ensureIndex(array("name" => 1, "ts" => -1));
SELECT * FROM users WHERE a=1 and b='q'
$db->users->find(array("a" => 1, "b" => "q"));
SELECT * FROM users LIMIT 10 SKIP 20
$db->users->find()->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2
$db->users->find(array('$or' => array(array("a" => 1), array("b" => 2))));
SELECT * FROM users LIMIT 1
$db->users->find()->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3
$db->users->find(array("z" => 3))->explain()
SELECT DISTINCT last_name FROM users
$db->command(array("distinct" => "users", "key" => "last_name"));
SELECT COUNT(*y) FROM users
$db->users->count();
SELECT COUNT(*y) FROM users where AGE > 30
$db->users->find(array("age" => array('$gt' => 30)))->count();
SELECT COUNT(AGE) from users
$db->users->find(array("age" => array('$exists' => true)))->count();
UPDATE users SET a=1 WHERE b='q'
$db->users->update(array("b" => "q"), array('$set' => array("a" => 1)));
UPDATE users SET a=a+2 WHERE b='q'
$db->users->update(array("b" => "q"), array('$inc => array("a" => 2)));
DELETE FROM users WHERE z="abc"
$db->users->remove(array("z" => "abc"));
 
sc.exe create MongoDB30 binPath= "d:\mongodb30\bin\mongod.exe -auth --logpath D:\mongodb\log\MongoDB.log --logappend --dbpath d:\mongodb\data --service " DisplayName= "MongoDB30" start= "auto"
 
//select * from test where name='joe'
db.test.find({"name":"joe"})

 

//不区分大小写的查询

db.test.find({"name":{"$regex":"WILLIAM","$options":"i"}})  

//select * from test where name='joe' limit 20

db.test.find({"name":"joe"}).limit(20)

 

 //类似mysql select * from test where name='joe' limit 20,20

db.test.find({"name":"joe"}).limit(20).skip(20)

 

 //select * from test where name like '%william%' 不含有

  • db.test.find({"name":/.*william.*/i})
  • //不含有
  • db.test.find({"name":{$not:/.*william.*/i}})
 //建立索引在字段name上,1(ascending),-1(descending)
db.test.ensureIndex({"name":1})

 

 //去掉字段email,

//alter table test drop email  

//multi:true 参数可省略,省略的意思是只删除第一行的email字段,multi:true代表删除全部行的email字段
db.test.update({},{$unset:{"email":""}},{multi:true})

 

 //查看表索引   

//show index from test
db.test.getIndexes()

 

 //修改collections名 

db.test.renameCollection("newtablename")

 

 //导出数据

//mysqldump -u test dbname tablename -p > "c:/db.sql"
mongoexport -d dbname -c tablename -u test -p -o "c:/db.json"
 

//导出csv格式

mongoexport -d dbname -c tablename -u test -p test -f "fieldname" -csv -o "c:/db.csv"

 

//往数据表news中导入数据,用户名为test

//mysql -u test -D test -p < "c:/db.sql"
mongoimport -d test -c news -u test -p password "c:/db.json" 

//找出name="joe"的记录中,该行是否含有atta.b这个字段

db.test.find({"name":"joe","atta.b":{$exists:true}}).count()

 

//找出name="joe"并且atta.b = "bbb"的记录

db.test.find({"name":"joe","atta.b":"bbb"}  

 

 //删除name='williamf'这条记录中的Email项为"aa@qq.com"的数值

db.test.update({"name":"william"},{"$pull":{"email":"aa@qq.com"}})

 //位置更新

//找到sn等于1的这条记录,找到stock.fnfp.pn等于"aa"这个位置,加入数据:"price":"555"
//前提是stock.fnfp为array类型
db.test.update({"sn" : "1","stock.fnfp.pn":"aa"} , {$push : { "stock.$.fnfp": {"price":"555"}}})

//往name="joe"的这些记录里添加内容atta.d = "ddd"

//前提是atta为array类型
db.test.update({"name":"joe"},{$push:{"atta":{"d":"ddd"}}})

 //update test set email='a.163.com' where name='joe'

db.test.update({"name":"joe"},{$set:{"email":"a.163.com"}})

 //查询所有name字段是字符类型的

db.test.find({name: {$type: 2}})

 //查询所有age字段是整型的

db.test.find({age: {$type: 16}})

 //查询以字母b或者B带头的所有记录

db.users.find({name: /^b.*/i})

 //查询 age > 18 的记录,以下查询都一样

db.users.find({age: {$gt: 18}})
db.users.find({$where: "this.age > 18"})
db.users.find("this.age > 18")
f = function() {return this.age > 18} db.users.find(f)

 //返回3条记录并打印信息

db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)})

结果

my age is 18
my age is 19
my age is 20
 
//复制news表数据到另一个表news_bak
//前提是news_bak为空表,或者两个表的_id不重复
db.news.find().forEach(function(x){db.news_bak.insert(x)})

 //显示你所有当前正在运行操作

db.currentOp()

 //可以用来杀掉长查询

db.killOp(opid)

 //显示你整个服务器的状态,对监控非常有用

db.serverStatus()

 //显示你选中库的状态

db.stats()

 //特定集的状态

db.collection.stats()

 //查看collection数据的大小

db.collection.dataSize()

 //查询所有索引的大小

db.collection.totalIndexSize()

 // 修改密码

db.changeUserPassword("reporting", "SOh3TbYhxuLiW8ypJPxmt1oOfL")

//删除字段中的某个值,该字段必须为array

{
"name":"joe"
"email":
   [
       "aaa@163.com",
       {"qqemail": "aa@qq.com"}
   ]
}
db.test.update({"name":"joe"},{$pull:{"email":"aaa@163.com"}})

或者:

db.test.update({"name":"joe"},{$pull:{"email":{"qqemail":"aa@qq.com"}}})
 
upsert
db.post.update({count:100},{"$inc":{count:10}},true)

在找不到count=100这条记录的时候,自动插入一条count=100,然后再加10,最后得到一条 count=110的记录

 

 //备份数据库dbname,bin下生成一个dbname.bak/dbname的目录
mongodump -h 127.0.0.1 -d dbname -u username -p -o d:/dbname.bak

 //还原数据库dbname

mongorestore -h 127.0.0.1 -d dbname -u username -p password dbname.bak/dbname

 //删除复杂的嵌套文档

db.test.find()
 
{
  "_id":ObjectId("52428f5d5ab08c5e801f7209"),
  "price":[
        {"digk":{"nt1":1,"nt2":2}},
        {"avn":{"nt1":22,"nt2":23}}
   ],
   "sn":1
}

 用javascript来执行mongodb

 

//删除字段price下的avn
方法一:
db.test.update({"sn":1},{$pop:{"price":0}}) 

移除price数组下的第0项

缺陷必须知道avn在price中的位置
 
方法三:
db.test.update({"sn":1},{$pull:{"price":{"avn":{"nt1":22,"nt2":23}}}})

缺陷必须知道price中的avn的

 
方法二:
var cursor=db.test.find();
while(cursor.hasNext()){
    var y=cursor.next();
    for(var i=0;i<y.price.length;i++){  
        delete y.price[i].avn;     
    }  
    db.test.save(y);
}

 

//给现有collections新增自增ID,字段名:sn
var cursor=db.test.find();
var i = 1;
while(cursor.hasNext()){   
    var y=cursor.next();
    var _id = y._id;
    db.test.update({"_id":_id},{$set:{"sn":i}});
    i++;
}

 // demo 存入如下文档

db.test.save({"sn":1,
"contact":
{
   "China":[
         {"city":"beijing","email":"a@163.com","tel":"010-6666"},
         {"city":"shanghai","email":"b@263.com","tel":"021-8888"},
         {"city":"shenzhen","email":"c@sohu.com","tel":"0755-9999"}
   ],
   "United-States":[
         {"city":"Newyork","email":"a@163.com","tel":"010-6666"},
         {"city":"Washington","email":"a@163.com","tel":"010-6666"}
   ]
}
})
 
db.test.save({"sn":2,
"contact":
{
   "Japan":[
         {"city":"tokyo","email":"a@163.com","tel":"010-6666"},
         {"city":"Osaka","email":"b@263.com","tel":"021-8888"},
         {"city":"Hokkaido","email":"c@sohu.com","tel":"0755-9999"}
   ],
   "Canada":[
         {"city":"Vancouver","email":"a@163.com","tel":"010-6666"},
         {"city":"Ottawa","email":"a@163.com","tel":"010-6666"}
   ]
}
})

 --删除China下,city为shenzhen的一组数据

var cursor = db.test.find({"sn":1});
while(cursor.hasNext()){
    var y = cursor.next();
    for(var i =0;i < y.contact.China.length;i++){
        if(y.contact.China[i].city == 'shenzhen'){
            delete y.contact.China[i];
        }
    }
    db.test.save(y);
   
}

 --将China下city为beijing 的,city改为guangzhou

db.test.update({"sn":1,"contact.China.city":"beijing"},{$set:{"contact.China.$.city":"guangzhou"}})

 --重命名collections  ,将usersinfo 重命名为users

db.usersinfo.renameCollection("users")
 // 释放内存
 db.runCommand({closeAllDatabases:1})  //mongodb3.0之后官方放弃了这个功能
 //mongodb 启动设置Mongodb运行内存大小,使之不能无限期吃内存
wireTigerCacheSizeGB=n //n为多少GB
 
//切割释放日志
db.runCommand({logRotate:1}) //windows
kill -SIGUSR1 pid //Linux下,pid是mongodb的进程号
 
//建唯一索引
 db.person.ensureIndex({firstname:1, lastname: 1},{unique: true});
 
//查看索引
 db.data.getIndexes()
mongorestore -d parts -directoryperdb d:\databackup\parts\
 
//使用存储过程
db.system.js.save({_id:"addNumbers",value:function(x,y){return x+y;}})
 
//查看存储过程
db.system.js.find()
 
//执行存储过程
db.eval("addNumbers(3,9);");
 
如果出现验证错误,那么需要对该登录用户进行角色授权:
1、建立sysadmin角色,
use admin
db.createRole({role:'sysadmin',roles:[],privileges:[{resource:{anyResource:true},actions:'anyAction']}]})
2、授权
use test
db.grantRolesToUser("test",[{role:'sysadmin',db:'admin'}])
 
 key:[{'id':123,'value':11},{'id':124,'value':12}] 

查询匹配key里id与value皆匹配:find({'key':{$elemMatch:{"id":123,"value":12}}})可以做到返回不出结果。

 更多信息尽在QQ群内:607021567

posted @ 2018-05-21 15:32  James·Sean  阅读(226)  评论(0编辑  收藏  举报