SQL to mongo Shell to C++

来源:互联网 发布:mac版梦幻西游鼠标右键 编辑:程序博客网 时间:2024/05/21 10:31

转载自:

http://mongodb-documentation.readthedocs.org/en/latest/ecosystem/drivers/cpp-to-sql-to-mongo-shell.html#sql-to-mongo-shell-to-cpp

Several of the C++ driver methods throw mongo::DBException, so you will want a try/catch statement as some level in your program. Also be sure to callc.getLastError() after writes to check the error code.

SQLmongo ShellC++ Driver
INSERT INTO USERSVALUES( 1, 1)
db.users.insert( { a: 1, b: 1 } )
// GENOID is optional. if not done by client,// server will add an _idc.insert("mydb.users",  BSON(GENOID<<"a"<<1<<"b"<<1));// then: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 usersWHERE 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 *FROM usersWHERE age=33ORDER 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 usersWHERE age>33AND age<=40
db.users.find( { 'age': { $gt:33, $lte:40 } } )
auto_ptr<DBClientCursor> cursor =  c.query("mydb.users",  QUERY("age"<<GT<<33<<LTE<<40));
CREATE INDEX myindexnameON users(name)
db.users.ensureIndex( {name: 1 } )
c.ensureIndex("mydb.users", BSON("name"<<1));
SELECT *FROM usersLIMIT 10SKIP 20
db.users.find().limit(10).skip(20)
auto_ptr<DBClientCursor> cursor =  c.query("mydb.users", Query(),          10, 20);
SELECT * FROM users LIMIT 1
db.users.findOne()
bo obj = c.findOne("mydb.users", Query());
SELECT DISTINCT last_nameFROM usersWHERE x=1
db.users.distinct( 'last_name', {x: 1} )
// no helper for distinct yet in c++ driver,// so send command manuallybo cmdResult;bool ok = c.runCommand(  "mydb",  BSON("distinct" << "users"                  << "key" << "last_name"                  << "query" << BSON("x"<<1)),  cmdResult);list<bo> results;cmdResult["values"].Obj().Vals(results);
SELECT COUNT(*)FROM userswhere AGE > 30
db.users.find( { age: { $gt: 30 } } ).count()
unsigned long long n =   c.count("mydb.users", BSON("age"<<GT<<30));
UPDATE usersSET a=a+2WHERE 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();
DELETEFROM usersWHERE z="abc"
db.users.remove( { z: 'abc' } )
c.remove("mydb.users", QUERY("z"<<"abc"));// then optionally:string err = c.getLastError();
0 0
原创粉丝点击