数据库

 首页 > 数据库 > MongoDB > MongoDB数据库使用总结

MongoDB数据库使用总结

分享到:
【字体:
导读:
         摘要:安装mongodb$#replace1.6.4intheurlbelowwiththeversionyouwant$curlhttp://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.6.4.tgzmongo.tgz$tarxzfmongo.tgz$cdmongo...

MongoDB数据库使用总结

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

mysql

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 cursor = c.query("mydb.users", Query(), 0, 0, BSON("a"<<1<<"b"<<1));

SELECT * FROM users

db.users.find()

auto_ptr cursor = c.query("mydb.users", Query());

SELECT * FROM users WHERE age=33

db.users.find({age:33})

auto_ptr cursor = c.query("mydb.users", QUERY("age"<<33))

// or:

auto_ptr 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 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 cursor = c.query("mydb.users", QUERY("age"<

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

list 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:"<

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

// 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                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,) 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 , )

        db.mycoll.remove(query)

        db.mycoll.renameCollection( newName , ) renames the collection.

        db.mycoll.runCommand( name , ) 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( ) - 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 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数据库使用总结
分享到:
MongoDB数据库基础命令
MongoDB数据库基础命令 如果想查看当前连接在哪个数据库下面,可以直接输入db CODE: > db Admin想切换到test数据库下面 CODE: > use test switched to db test > db Test想查看test下有哪些表或者叫collection,可以输入 CODE: > show collections system.indexes user想知道mongodb支持哪些命令,可...
MySQL与MongoDB数据库设计中的比较
MySQL与MongoDB数据库设计中的比较 MySQL是关系型数据库中的明星,MongoDB是文档型数据库中的翘楚。下面通过一个设计实例对比一下二者:假设我们正在维护一个手机产品库,里面除了包含手机的名称,品牌等基本信息,还包含了待机时间,外观设计等参数信息,应该如何存取数据呢? 如果使用MySQL的话,应该如何存取数据呢...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……