mongodb使用总结1

安装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;

Java代码 
  1. import java.net.UnknownHostException;  
  2. import java.util.Set;  
  3.   
  4. import com.mongodb.BasicDBObject;  
  5. import com.mongodb.DB;  
  6. import com.mongodb.DBCollection;  
  7. import com.mongodb.DBCursor;  
  8. import com.mongodb.Mongo;  
  9. import com.mongodb.MongoException;  
  10.   
  11. public class MongoDemo1 {  
  12.   
  13.     public static void main(String[] args) throws UnknownHostException, MongoException {  
  14.   
  15.         Mongo m = new Mongo("10.20.150.205"27017);  
  16.   
  17.         DB db = m.getDB("test");  
  18.           
  19.         Set<String> colls = db.getCollectionNames();  
  20.   
  21.         for (String s : colls) {  
  22.             System.out.println(s);  
  23.         }  
  24.           
  25.         DBCollection coll = db.getCollection("testCol");  
  26.           
  27.         BasicDBObject doc = new BasicDBObject();  
  28.   
  29.         doc.put("name""MongoDB");  
  30.         doc.put("type""database");  
  31.         doc.put("count"1);  
  32.   
  33.         BasicDBObject info = new BasicDBObject();  
  34.   
  35.         info.put("x"203);  
  36.         info.put("y"102);  
  37.   
  38.         doc.put("info", info);  
  39.   
  40.         coll.insert(doc);  
  41.           
  42.         System.out.println(coll.getCount());  
  43.   
  44.         DBCursor cur = coll.find();  
  45.   
  46.         while(cur.hasNext()) {  
  47.             System.out.println(cur.next());  
  48.         }  
  49.           
  50.         BasicDBObject query = new BasicDBObject();  
  51.   
  52.         query.put("type""database");  
  53.   
  54.         cur = coll.find(query);  
  55.   
  56.         while(cur.hasNext()) {  
  57.             System.out.println(cur.next());  
  58.         }  
  59.     }  
  60. }  

 

输出:

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}}


posted @ 2012-05-31 13:32  zhwj184  阅读(206)  评论(0编辑  收藏  举报