mongodb使用总结
来源:互联网 发布:淘宝手机助手官方版 编辑:程序博客网 时间:2024/05/21 20:29
from:http://zhwj184.iteye.com/blog/1068443
安装mongodb
$ # replace "1.6.4" in the url below with the version you want
$ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.6.4.tgz > mongo.tgz
$ tar xzf mongo.tgz
$ cd mongo
$./mongod #启动服务器
$./mongo #启动客户端
1.mongodb 命令列表
Mongo查询语法与SQL语法对照表
MySQL executable
Oracle executable
Mongo executable
mysqld
oracle
mongod
mysql
sqlplus
mongo
mongodb查询语法与SQL语法对比
SQL Statement
Mongo Query Language Statement
C++客户端调用语法
using namespace bson;
DBClientConnection c;
c.connect("somehost");
CREATE TABLE USERS (aNumber, b Number)
db.createCollection("mycoll")
INSERT INTO USERS VALUES(1,1)
db.users.insert({a:1,b:1})
// GENOID is optional. if not done by client, server will add an _id
c.insert("mydb.users", BSON(GENOID<<"a"<<1<<"b"<<1));
// then optionally:
string err = c.getLastError();
SELECT a,b FROM users
db.users.find({}, {a:1,b:1})
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", Query(), 0, 0, BSON("a"<<1<<"b"<<1));
SELECT * FROM users
db.users.find()
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", Query());
SELECT * FROM users WHERE age=33
db.users.find({age:33})
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", QUERY("age"<<33))
// or:
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", BSON("age"<<33))
SELECT a,b FROM users WHERE age=33
db.users.find({age:33}, {a:1,b:1})
SELECT * FROM users WHERE age=33 ORDER BY name
db.users.find({age:33}).sort({name:1})
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", QUERY("age"<<33).sort("name"));
SELECT * FROM users WHERE age>33
db.users.find({'age':{$gt:33}})})
SELECT * FROM users WHERE age<33
db.users.find({'age':{$lt:33}})})
SELECT * FROM users WHERE name LIKE "%Joe%"
db.users.find({name:/Joe/})
SELECT * FROM users WHERE name LIKE "Joe%"
db.users.find({name:/^Joe/})
SELECT * FROM users WHERE age>33 AND age<=40
db.users.find({'age':{$gt:33,$lte:40}})})
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", QUERY("age"<<GT<<33<<LTE<<40));
SELECT * FROM users ORDER BY name DESC
db.users.find().sort({name:-1})
SELECT * FROM users WHERE a=1 and b='q'
db.users.find({a:1,b:'q'})
SELECT * FROM users LIMIT 10 SKIP 20
db.users.find().limit(10).skip(20)
auto_ptr<DBClientCursor> cursor = c.query("mydb.users", Query(), 10, 20);
SELECT * FROM users WHERE a=1 or b=2
db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } )
SELECT * FROM users LIMIT 1
db.users.findOne()
bo obj = c.findOne("mydb.users", Query());
SELECT DISTINCT last_name FROM users
db.users.distinct('last_name')
// no helper for distinct in c++ driver, so send command manually
bo cmdResult;
bool ok = c.runCommand("mydb", BSON("distinct"<<"users"<<key<<"last_name"), cmdResult);
list<bo> results;
cmdResult["values"].Obj().Vals(results);
SELECT COUNT(*y)
FROM users
db.users.count()
SELECT COUNT(*y)
FROM users where AGE > 30
db.users.find({age: {'$gt': 30}}).count()
unsigned long long n = c.count("mydb.users", QUERY("age:"<<GT<<30));
SELECT COUNT(AGE) from users
db.users.find({age: {'$exists':true}}).count()
CREATE INDEX myindexname ON users(name)
db.users.ensureIndex({name:1})
c.ensureIndex("mydb.users", BSON("name"<<1));
CREATE INDEX myindexname ON users(name,ts DESC)
db.users.ensureIndex({name:1,ts:-1})
EXPLAIN SELECT * FROM users WHERE z=3
db.users.find({z:3}).explain()
UPDATE users SET a=1 WHERE b='q'
db.users.update({b:'q'}, {$set:{a:1}}, false,true)
UPDATE users SET a=a+2 WHERE b='q'
db.users.update({b:'q'}, {$inc:{a:2}}, false,true)
c.update("mydb.users", QUERY("b"<<"q"), BSON("$inc"<<BSON("a"<<2)), false, true);
// then optionally:
string err = c.getLastError();
bool ok = err.empty();
DELETE FROM users WHERE z="abc"
db.users.remove({z:'abc'});
c.remove("mydb.users", QUERY("z"<<"abc"));
// then optionally:
string err = c.getLastError();
命令帮助列表:
使用mongo进入交互式客户端:
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
rs.help() help on replica set methods
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
> db.help()
DB methods:
db.addUser(username, password[, readOnly=false])
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.currentOp() displays the current operation in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.printCollectionStats()
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()
db.removeUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
db.shutdownServer()
db.stats()
db.version() current version of the server
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnock() unlocks server following a db.fsyncLock()
> db.mycoll.help()
DBCollection help
db.mycoll.find().help() - show DBCursor help
db.mycoll.count()
db.mycoll.dataSize()
db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' )
db.mycoll.drop() drop the collection
db.mycoll.dropIndex(name)
db.mycoll.dropIndexes()
db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
db.mycoll.reIndex()
db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.mycoll.find( {x:77} , {name:1, x:1} )
db.mycoll.find(...).count()
db.mycoll.find(...).limit(n)
db.mycoll.find(...).skip(n)
db.mycoll.find(...).sort(...)
db.mycoll.findOne([query])
db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
db.mycoll.getDB() get DB object associated with collection
db.mycoll.getIndexes()
db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )
db.mycoll.remove(query)
db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection.
db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
db.mycoll.save(obj)
db.mycoll.stats()
db.mycoll.storageSize() - includes free space allocated to this collection
db.mycoll.totalIndexSize() - size in bytes of all the indexes
db.mycoll.totalSize() - storage allocated for all data and indexes
db.mycoll.update(query, object[, upsert_bool, multi_bool])
db.mycoll.validate( <full> ) - SLOW
db.mycoll.getShardVersion() - only for use with sharding
> db.users.find() #users是collection的名称
{ "_id" : ObjectId("4de71d5faf575684b391b8db"), "a" : 1, "b" : 1 }
> show dbs
admin (empty)
local (empty)
test 0.203125GB
> show collections
mycoll
system.indexes
testCollection
users
>
java端调用
1到https://github.com/mongodb/mongo-java-driver/downloads 下载java客户端需要的jar,引入工程里面,
2.
package com.alibaba.asc.demoLearnCenter.mongo;
- import java.net.UnknownHostException;
- import java.util.Set;
- import com.mongodb.BasicDBObject;
- import com.mongodb.DB;
- import com.mongodb.DBCollection;
- import com.mongodb.DBCursor;
- import com.mongodb.Mongo;
- import com.mongodb.MongoException;
- public class MongoDemo1 {
- public static void main(String[] args) throws UnknownHostException, MongoException {
- Mongo m = new Mongo("10.20.150.205", 27017);
- DB db = m.getDB("test");
- Set<String> colls = db.getCollectionNames();
- for (String s : colls) {
- System.out.println(s);
- }
- DBCollection coll = db.getCollection("testCol");
- BasicDBObject doc = new BasicDBObject();
- doc.put("name", "MongoDB");
- doc.put("type", "database");
- doc.put("count", 1);
- BasicDBObject info = new BasicDBObject();
- info.put("x", 203);
- info.put("y", 102);
- doc.put("info", info);
- coll.insert(doc);
- System.out.println(coll.getCount());
- DBCursor cur = coll.find();
- while(cur.hasNext()) {
- System.out.println(cur.next());
- }
- BasicDBObject query = new BasicDBObject();
- query.put("type", "database");
- cur = coll.find(query);
- while(cur.hasNext()) {
- System.out.println(cur.next());
- }
- }
- }
输出:
mycoll
system.indexes
testCollection
users
1
{ "_id" : { "$oid" : "4de72c04a1f3a9ef7fc0c750"} , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4de72c04a1f3a9ef7fc0c750"} , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
- mongodb使用总结1
- mongodb使用总结
- mongodb mapreduce使用总结
- mongodb 使用总结
- Mongodb使用总结
- MongoDB使用总结
- mongodb使用简单总结
- mongodb使用总结
- Mongodb总结4-Spring环境使用Mongodb
- 使用MongoDB类操作MongoDB数据库总结
- MongoDB错误和使用总结
- Mongodb的主从复制使用总结
- MongoDB Replica Set使用几点总结
- Mongodb知识及使用总结(一)
- MongoDB使用总结(C#版 潘鹏)
- Spring MVC中使用Mongodb总结
- nodejs初期开发总结--MongoDB使用常识
- Spring MVC中使用Mongodb总结
- c# 写入xml
- MVC 最佳实践
- 孙鑫VC学习笔记:第十五讲 编写一个基于MFC对话框的聊天程序
- poj 2632
- View中Draw方法
- mongodb使用总结
- 探索 Pexpect,第 1 部分:剖析 Pexpect
- MyEclipse编码设置
- 守护进程
- 1017. Rate of Return (用二分法求近似解)
- COM组件注册真相(转)
- iOS的三维透视投影
- 《Effective STL》读书笔记四:Item 6 - 9
- 探索 Pexpect,第 2 部分:Pexpect 的实例分析