diff options
Diffstat (limited to 'src/mongo/client/examples')
-rw-r--r-- | src/mongo/client/examples/authTest.cpp | 54 | ||||
-rw-r--r-- | src/mongo/client/examples/clientTest.cpp | 279 | ||||
-rw-r--r-- | src/mongo/client/examples/first.cpp | 86 | ||||
-rw-r--r-- | src/mongo/client/examples/httpClientTest.cpp | 58 | ||||
-rw-r--r-- | src/mongo/client/examples/insert_demo.cpp | 47 | ||||
-rw-r--r-- | src/mongo/client/examples/mongoperf.cpp | 269 | ||||
-rwxr-xr-x | src/mongo/client/examples/mongoperf.vcxproj | 113 | ||||
-rwxr-xr-x | src/mongo/client/examples/mongoperf.vcxproj.filters | 73 | ||||
-rw-r--r-- | src/mongo/client/examples/rs.cpp | 118 | ||||
-rw-r--r-- | src/mongo/client/examples/second.cpp | 56 | ||||
-rwxr-xr-x | src/mongo/client/examples/simple_client_demo.vcxproj | 107 | ||||
-rwxr-xr-x | src/mongo/client/examples/simple_client_demo.vcxproj.filters | 17 | ||||
-rw-r--r-- | src/mongo/client/examples/tail.cpp | 46 | ||||
-rw-r--r-- | src/mongo/client/examples/tutorial.cpp | 71 | ||||
-rw-r--r-- | src/mongo/client/examples/whereExample.cpp | 69 |
15 files changed, 1463 insertions, 0 deletions
diff --git a/src/mongo/client/examples/authTest.cpp b/src/mongo/client/examples/authTest.cpp new file mode 100644 index 00000000000..71cdd390cff --- /dev/null +++ b/src/mongo/client/examples/authTest.cpp @@ -0,0 +1,54 @@ +// authTest.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <iostream> + +#include "client/dbclient.h" + +using namespace mongo; + +int main( int argc, const char **argv ) { + + const char *port = "27017"; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = argv[ 2 ]; + } + + DBClientConnection conn; + string errmsg; + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + + { + // clean up old data from any previous tests + conn.remove( "test.system.users" , BSONObj() ); + } + + conn.insert( "test.system.users" , BSON( "user" << "eliot" << "pwd" << conn.createPasswordDigest( "eliot" , "bar" ) ) ); + + errmsg.clear(); + bool ok = conn.auth( "test" , "eliot" , "bar" , errmsg ); + if ( ! ok ) + cout << errmsg << endl; + MONGO_assert( ok ); + + MONGO_assert( ! conn.auth( "test" , "eliot" , "bars" , errmsg ) ); +} diff --git a/src/mongo/client/examples/clientTest.cpp b/src/mongo/client/examples/clientTest.cpp new file mode 100644 index 00000000000..aaea6bd1bdf --- /dev/null +++ b/src/mongo/client/examples/clientTest.cpp @@ -0,0 +1,279 @@ +// clientTest.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * a simple test for the c++ driver + */ + +// this header should be first to ensure that it includes cleanly in any context +#include "client/dbclient.h" + +#include <iostream> + +#ifndef assert +# define assert(x) MONGO_assert(x) +#endif + +using namespace std; +using namespace mongo; + +int main( int argc, const char **argv ) { + + const char *port = "27017"; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = argv[ 2 ]; + } + + DBClientConnection conn; + string errmsg; + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + + const char * ns = "test.test1"; + + conn.dropCollection(ns); + + // clean up old data from any previous tests + conn.remove( ns, BSONObj() ); + assert( conn.findOne( ns , BSONObj() ).isEmpty() ); + + // test insert + conn.insert( ns ,BSON( "name" << "eliot" << "num" << 1 ) ); + assert( ! conn.findOne( ns , BSONObj() ).isEmpty() ); + + // test remove + conn.remove( ns, BSONObj() ); + assert( conn.findOne( ns , BSONObj() ).isEmpty() ); + + + // insert, findOne testing + conn.insert( ns , BSON( "name" << "eliot" << "num" << 1 ) ); + { + BSONObj res = conn.findOne( ns , BSONObj() ); + assert( strstr( res.getStringField( "name" ) , "eliot" ) ); + assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); + assert( 1 == res.getIntField( "num" ) ); + } + + + // cursor + conn.insert( ns ,BSON( "name" << "sara" << "num" << 2 ) ); + { + auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() ); + int count = 0; + while ( cursor->more() ) { + count++; + BSONObj obj = cursor->next(); + } + assert( count == 2 ); + } + + { + auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 1 ) ); + int count = 0; + while ( cursor->more() ) { + count++; + BSONObj obj = cursor->next(); + } + assert( count == 1 ); + } + + { + auto_ptr<DBClientCursor> cursor = conn.query( ns , BSON( "num" << 3 ) ); + int count = 0; + while ( cursor->more() ) { + count++; + BSONObj obj = cursor->next(); + } + assert( count == 0 ); + } + + // update + { + BSONObj res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); + assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); + + BSONObj after = BSONObjBuilder().appendElements( res ).append( "name2" , "h" ).obj(); + + conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after ); + res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); + assert( ! strstr( res.getStringField( "name2" ) , "eliot" ) ); + assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); + + conn.update( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() , after ); + res = conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ); + assert( strstr( res.getStringField( "name" ) , "eliot" ) ); + assert( strstr( res.getStringField( "name2" ) , "h" ) ); + assert( conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() ).isEmpty() ); + + // upsert + conn.update( ns , BSONObjBuilder().append( "name" , "eliot2" ).obj() , after , 1 ); + assert( ! conn.findOne( ns , BSONObjBuilder().append( "name" , "eliot" ).obj() ).isEmpty() ); + + } + + { + // ensure index + assert( conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); + assert( ! conn.ensureIndex( ns , BSON( "name" << 1 ) ) ); + } + + { + // hint related tests + assert( conn.findOne(ns, "{}")["name"].str() == "sara" ); + + assert( conn.findOne(ns, "{ name : 'eliot' }")["name"].str() == "eliot" ); + assert( conn.getLastError() == "" ); + + // nonexistent index test + bool asserted = false; + try { + conn.findOne(ns, Query("{name:\"eliot\"}").hint("{foo:1}")); + } + catch ( ... ) { + asserted = true; + } + assert( asserted ); + + //existing index + assert( conn.findOne(ns, Query("{name:'eliot'}").hint("{name:1}")).hasElement("name") ); + + // run validate + assert( conn.validate( ns ) ); + } + + { + // timestamp test + + const char * tsns = "test.tstest1"; + conn.dropCollection( tsns ); + + { + mongo::BSONObjBuilder b; + b.appendTimestamp( "ts" ); + conn.insert( tsns , b.obj() ); + } + + mongo::BSONObj out = conn.findOne( tsns , mongo::BSONObj() ); + Date_t oldTime = out["ts"].timestampTime(); + unsigned int oldInc = out["ts"].timestampInc(); + + { + mongo::BSONObjBuilder b1; + b1.append( out["_id"] ); + + mongo::BSONObjBuilder b2; + b2.append( out["_id"] ); + b2.appendTimestamp( "ts" ); + + conn.update( tsns , b1.obj() , b2.obj() ); + } + + BSONObj found = conn.findOne( tsns , mongo::BSONObj() ); + cout << "old: " << out << "\nnew: " << found << endl; + assert( ( oldTime < found["ts"].timestampTime() ) || + ( oldTime == found["ts"].timestampTime() && oldInc < found["ts"].timestampInc() ) ); + + } + + { + // check that killcursors doesn't affect last error + assert( conn.getLastError().empty() ); + + BufBuilder b; + b.appendNum( (int)0 ); // reserved + b.appendNum( (int)-1 ); // invalid # of cursors triggers exception + b.appendNum( (int)-1 ); // bogus cursor id + + Message m; + m.setData( dbKillCursors, b.buf(), b.len() ); + + // say() is protected in DBClientConnection, so get superclass + static_cast< DBConnector* >( &conn )->say( m ); + + assert( conn.getLastError().empty() ); + } + + { + list<string> l = conn.getDatabaseNames(); + for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) { + cout << "db name : " << *i << endl; + } + + l = conn.getCollectionNames( "test" ); + for ( list<string>::iterator i = l.begin(); i != l.end(); i++ ) { + cout << "coll name : " << *i << endl; + } + } + + { + //Map Reduce (this mostly just tests that it compiles with all output types) + const string ns = "test.mr"; + conn.insert(ns, BSON("a" << 1)); + conn.insert(ns, BSON("a" << 1)); + + const char* map = "function() { emit(this.a, 1); }"; + const char* reduce = "function(key, values) { return Array.sum(values); }"; + + const string outcoll = ns + ".out"; + + BSONObj out; + out = conn.mapreduce(ns, map, reduce, BSONObj()); // default to inline + //MONGO_PRINT(out); + out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll); + //MONGO_PRINT(out); + out = conn.mapreduce(ns, map, reduce, BSONObj(), outcoll.c_str()); + //MONGO_PRINT(out); + out = conn.mapreduce(ns, map, reduce, BSONObj(), BSON("reduce" << outcoll)); + //MONGO_PRINT(out); + } + + { + // test timeouts + + DBClientConnection conn( true , 0 , 2 ); + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + conn.insert( "test.totest" , BSON( "x" << 1 ) ); + BSONObj res; + + bool gotError = false; + assert( conn.eval( "test" , "return db.totest.findOne().x" , res ) ); + try { + conn.eval( "test" , "sleep(5000); return db.totest.findOne().x" , res ); + } + catch ( std::exception& e ) { + gotError = true; + log() << e.what() << endl; + } + assert( gotError ); + // sleep so the server isn't locked anymore + sleepsecs( 4 ); + + assert( conn.eval( "test" , "return db.totest.findOne().x" , res ) ); + + + } + + cout << "client test finished!" << endl; +} diff --git a/src/mongo/client/examples/first.cpp b/src/mongo/client/examples/first.cpp new file mode 100644 index 00000000000..ab5efb325f5 --- /dev/null +++ b/src/mongo/client/examples/first.cpp @@ -0,0 +1,86 @@ +// first.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * this is a good first example of how to use mongo from c++ + */ + +#include <iostream> + +#include "client/dbclient.h" + +using namespace std; + +void insert( mongo::DBClientConnection & conn , const char * name , int num ) { + mongo::BSONObjBuilder obj; + obj.append( "name" , name ); + obj.append( "num" , num ); + conn.insert( "test.people" , obj.obj() ); +} + +int main( int argc, const char **argv ) { + + const char *port = "27017"; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = argv[ 2 ]; + } + + mongo::DBClientConnection conn; + string errmsg; + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + + { + // clean up old data from any previous tests + mongo::BSONObjBuilder query; + conn.remove( "test.people" , query.obj() ); + } + + insert( conn , "eliot" , 15 ); + insert( conn , "sara" , 23 ); + + { + mongo::BSONObjBuilder query; + auto_ptr<mongo::DBClientCursor> cursor = conn.query( "test.people" , query.obj() ); + cout << "using cursor" << endl; + while ( cursor->more() ) { + mongo::BSONObj obj = cursor->next(); + cout << "\t" << obj.jsonString() << endl; + } + + } + + { + mongo::BSONObjBuilder query; + query.append( "name" , "eliot" ); + mongo::BSONObj res = conn.findOne( "test.people" , query.obj() ); + cout << res.isEmpty() << "\t" << res.jsonString() << endl; + } + + { + mongo::BSONObjBuilder query; + query.append( "name" , "asd" ); + mongo::BSONObj res = conn.findOne( "test.people" , query.obj() ); + cout << res.isEmpty() << "\t" << res.jsonString() << endl; + } + + +} diff --git a/src/mongo/client/examples/httpClientTest.cpp b/src/mongo/client/examples/httpClientTest.cpp new file mode 100644 index 00000000000..4055d4492d5 --- /dev/null +++ b/src/mongo/client/examples/httpClientTest.cpp @@ -0,0 +1,58 @@ +// httpClientTest.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <iostream> + +#include "client/dbclient.h" +#include "util/net/httpclient.h" + +using namespace mongo; + +void play( string url ) { + cout << "[" << url << "]" << endl; + + HttpClient c; + HttpClient::Result r; + MONGO_assert( c.get( url , &r ) == 200 ); + + HttpClient::Headers h = r.getHeaders(); + MONGO_assert( h["Content-Type"].find( "text/html" ) == 0 ); + + cout << "\tHeaders" << endl; + for ( HttpClient::Headers::iterator i = h.begin() ; i != h.end(); ++i ) { + cout << "\t\t" << i->first << "\t" << i->second << endl; + } + +} + +int main( int argc, const char **argv ) { + + int port = 27017; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = atoi( argv[ 2 ] ); + } + port += 1000; + + play( str::stream() << "http://localhost:" << port << "/" ); + +#ifdef MONGO_SSL + play( "https://www.10gen.com/" ); +#endif + +} diff --git a/src/mongo/client/examples/insert_demo.cpp b/src/mongo/client/examples/insert_demo.cpp new file mode 100644 index 00000000000..14ac79ee1a0 --- /dev/null +++ b/src/mongo/client/examples/insert_demo.cpp @@ -0,0 +1,47 @@ +/* + C++ client program which inserts documents in a MongoDB database. + + How to build and run: + + Using mongo_client_lib.cpp: + g++ -I .. -I ../.. insert_demo.cpp ../mongo_client_lib.cpp -lboost_thread-mt -lboost_filesystem + ./a.out +*/ + +#include <iostream> +#include "dbclient.h" // the mongo c++ driver + +using namespace std; +using namespace mongo; +using namespace bson; + +int main() { + try { + cout << "connecting to localhost..." << endl; + DBClientConnection c; + c.connect("localhost"); + cout << "connected ok" << endl; + + bo o = BSON( "hello" << "world" ); + + cout << "inserting..." << endl; + + time_t start = time(0); + for( unsigned i = 0; i < 1000000; i++ ) { + c.insert("test.foo", o); + } + + // wait until all operations applied + cout << "getlasterror returns: \"" << c.getLastError() << '"' << endl; + + time_t done = time(0); + time_t dt = done-start; + cout << dt << " seconds " << 1000000/dt << " per second" << endl; + } + catch(DBException& e) { + cout << "caught DBException " << e.toString() << endl; + return 1; + } + + return 0; +} diff --git a/src/mongo/client/examples/mongoperf.cpp b/src/mongo/client/examples/mongoperf.cpp new file mode 100644 index 00000000000..68ebd6b10f2 --- /dev/null +++ b/src/mongo/client/examples/mongoperf.cpp @@ -0,0 +1,269 @@ +/* + How to build and run: + + scons mongoperf + ./mongoperf -h +*/ + +#define MONGO_EXPOSE_MACROS 1 + +#include <iostream> +#include "../dbclient.h" // the mongo c++ driver +#include "../../util/mmap.h" +#include <assert.h> +#include "../../util/logfile.h" +#include "../../util/timer.h" +#include "../../util/time_support.h" +#include "../../bson/util/atomic_int.h" + +using namespace std; +using namespace mongo; +using namespace bson; + +int dummy; +LogFile *lf = 0; +MemoryMappedFile *mmfFile; +char *mmf = 0; +bo options; +unsigned long long len; // file len +const unsigned PG = 4096; +unsigned nThreadsRunning = 0; + +// as this is incremented A LOT, at some point this becomes a bottleneck if very high ops/second (in cache) things are happening. +AtomicUInt iops; + +SimpleMutex m("mperf"); + +int syncDelaySecs = 0; + +void syncThread() { + while( 1 ) { + mongo::Timer t; + mmfFile->flush(true); + cout << " mmf sync took " << t.millis() << "ms" << endl; + sleepsecs(syncDelaySecs); + } +} + +char* round(char* x) { + size_t f = (size_t) x; + char *p = (char *) ((f+PG-1)/PG*PG); + return p; +} + +struct Aligned { + char x[8192]; + char* addr() { return round(x); } +}; + +unsigned long long rrand() { + // RAND_MAX is very small on windows + return (static_cast<unsigned long long>(rand()) << 15) ^ rand(); +} + +void workerThread() { + bool r = options["r"].trueValue(); + bool w = options["w"].trueValue(); + //cout << "read:" << r << " write:" << w << endl; + long long su = options["sleepMicros"].numberLong(); + Aligned a; + while( 1 ) { + unsigned long long rofs = (rrand() * PG) % len; + unsigned long long wofs = (rrand() * PG) % len; + if( mmf ) { + if( r ) { + dummy += mmf[rofs]; + iops++; + } + if( w ) { + mmf[wofs] = 3; + iops++; + } + } + else { + if( r ) { + lf->readAt(rofs, a.addr(), PG); + iops++; + } + if( w ) { + lf->writeAt(wofs, a.addr(), PG); + iops++; + } + } + long long micros = su / nThreadsRunning; + if( micros ) { + sleepmicros(micros); + } + } +} + +void go() { + assert( options["r"].trueValue() || options["w"].trueValue() ); + MemoryMappedFile f; + cout << "creating test file size:"; + len = options["fileSizeMB"].numberLong(); + if( len == 0 ) len = 1; + cout << len << "MB ..." << endl; + + if( 0 && len > 2000 && !options["mmf"].trueValue() ) { + // todo make tests use 64 bit offsets in their i/o -- i.e. adjust LogFile::writeAt and such + cout << "\nsizes > 2GB not yet supported with mmf:false" << endl; + return; + } + len *= 1024 * 1024; + const char *fname = "./mongoperf__testfile__tmp"; + try { + boost::filesystem::remove(fname); + } + catch(...) { + cout << "error deleting file " << fname << endl; + return; + } + lf = new LogFile(fname,true); + const unsigned sz = 1024 * 1024 * 32; // needs to be big as we are using synchronousAppend. if we used a regular MongoFile it wouldn't have to be + char *buf = (char*) malloc(sz+4096); + const char *p = round(buf); + for( unsigned long long i = 0; i < len; i += sz ) { + lf->synchronousAppend(p, sz); + if( i % (1024ULL*1024*1024) == 0 && i ) { + cout << i / (1024ULL*1024*1024) << "GB..." << endl; + } + } + BSONObj& o = options; + + if( o["mmf"].trueValue() ) { + delete lf; + lf = 0; + mmfFile = new MemoryMappedFile(); + mmf = (char *) mmfFile->map(fname); + assert( mmf ); + + syncDelaySecs = options["syncDelay"].numberInt(); + if( syncDelaySecs ) { + boost::thread t(syncThread); + } + } + + cout << "testing..."<< endl; + + unsigned wthr = (unsigned) o["nThreads"].Int(); + if( wthr < 1 ) { + cout << "bad threads field value" << endl; + return; + } + unsigned i = 0; + unsigned d = 1; + unsigned &nthr = nThreadsRunning; + while( 1 ) { + if( i++ % 8 == 0 ) { + if( nthr < wthr ) { + while( nthr < wthr && nthr < d ) { + nthr++; + boost::thread w(workerThread); + } + cout << "new thread, total running : " << nthr << endl; + d *= 2; + } + } + sleepsecs(1); + unsigned long long w = iops.get(); + iops.zero(); + w /= 1; // 1 secs + cout << w << " ops/sec "; + if( mmf == 0 ) + // only writing 4 bytes with mmf so we don't say this + cout << (w * PG / 1024 / 1024) << " MB/sec"; + cout << endl; + } +} + +int main(int argc, char *argv[]) { + + try { + cout << "mongoperf" << endl; + + if( argc > 1 ) { +cout << + +"\n" +"usage:\n" +"\n" +" mongoperf < myjsonconfigfile\n" +"\n" +" {\n" +" nThreads:<n>, // number of threads (default 1)\n" +" fileSizeMB:<n>, // test file size (default 1MB)\n" +" sleepMicros:<n>, // pause for sleepMicros/nThreads between each operation (default 0)\n" +" mmf:<bool>, // if true do i/o's via memory mapped files (default false)\n" +" r:<bool>, // do reads (default false)\n" +" w:<bool>, // do writes (default false)\n" +" syncDelay:<n> // secs between fsyncs, like --syncdelay in mongod. (default 0/never)\n" +" }\n" +"\n" +"mongoperf is a performance testing tool. the initial tests are of disk subsystem performance; \n" +" tests of mongos and mongod will be added later.\n" +"most fields are optional.\n" +"non-mmf io is direct io (no caching). use a large file size to test making the heads\n" +" move significantly and to avoid i/o coalescing\n" +"mmf io uses caching (the file system cache).\n" +"\n" + +<< endl; + return 0; + } + + cout << "use -h for help" << endl; + + char input[1024]; + memset(input, 0, sizeof(input)); + cin.read(input, 1000); + if( *input == 0 ) { + cout << "error no options found on stdin for mongoperf" << endl; + return 2; + } + + string s = input; + str::stripTrailing(s, "\n\r\0x1a"); + try { + options = fromjson(s); + } + catch(...) { + cout << s << endl; + cout << "couldn't parse json options" << endl; + return -1; + } + cout << "options:\n" << options.toString() << endl; + + go(); +#if 0 + cout << "connecting to localhost..." << endl; + DBClientConnection c; + c.connect("localhost"); + cout << "connected ok" << endl; + unsigned long long count = c.count("test.foo"); + cout << "count of exiting documents in collection test.foo : " << count << endl; + + bo o = BSON( "hello" << "world" ); + c.insert("test.foo", o); + + string e = c.getLastError(); + if( !e.empty() ) { + cout << "insert #1 failed: " << e << endl; + } + + // make an index with a unique key constraint + c.ensureIndex("test.foo", BSON("hello"<<1), /*unique*/true); + + c.insert("test.foo", o); // will cause a dup key error on "hello" field + cout << "we expect a dup key error here:" << endl; + cout << " " << c.getLastErrorDetailed().toString() << endl; +#endif + } + catch(DBException& e) { + cout << "caught DBException " << e.toString() << endl; + return 1; + } + + return 0; +} + diff --git a/src/mongo/client/examples/mongoperf.vcxproj b/src/mongo/client/examples/mongoperf.vcxproj new file mode 100755 index 00000000000..89168370733 --- /dev/null +++ b/src/mongo/client/examples/mongoperf.vcxproj @@ -0,0 +1,113 @@ +<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{79D4E297-BFB7-4FF2-9B13-08A146582E46}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <RootNamespace>mongoperf</RootNamespace>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup>
+ <ConfigurationType>Application</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <UseDebugLibraries>true</UseDebugLibraries>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <IncludePath>..\..;..\..\third_party\pcre-7.4;$(IncludePath)</IncludePath>
+ <LibraryPath>\boost\lib\vs2010_32;$(LibraryPath)</LibraryPath>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+ <ItemDefinitionGroup>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>c:\boost;\boost</AdditionalIncludeDirectories>
+ </ClCompile>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions> _CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories>c:\boost;\boost</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <AdditionalDependencies>ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions> _CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ <AdditionalDependencies>ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="..\..\util\logfile.cpp" />
+ <ClCompile Include="..\..\util\mmap.cpp" />
+ <ClCompile Include="..\..\util\mmap_win.cpp" />
+ <ClCompile Include="..\mongo_client_lib.cpp" />
+ <ClCompile Include="mongoperf.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="..\..\bson\bson-inl.h" />
+ <ClInclude Include="..\..\bson\bson.h" />
+ <ClInclude Include="..\..\bson\bsonelement.h" />
+ <ClInclude Include="..\..\bson\bsonmisc.h" />
+ <ClInclude Include="..\..\bson\bsonobj.h" />
+ <ClInclude Include="..\..\bson\bsonobjbuilder.h" />
+ <ClInclude Include="..\..\bson\bsonobjiterator.h" />
+ <ClInclude Include="..\..\bson\bsontypes.h" />
+ <ClInclude Include="..\..\bson\bson_db.h" />
+ <ClInclude Include="..\..\bson\inline_decls.h" />
+ <ClInclude Include="..\..\bson\oid.h" />
+ <ClInclude Include="..\..\bson\ordering.h" />
+ <ClInclude Include="..\..\bson\stringdata.h" />
+ <ClInclude Include="..\..\util\logfile.h" />
+ <ClInclude Include="..\..\util\mmap.h" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project>
\ No newline at end of file diff --git a/src/mongo/client/examples/mongoperf.vcxproj.filters b/src/mongo/client/examples/mongoperf.vcxproj.filters new file mode 100755 index 00000000000..ab12575af08 --- /dev/null +++ b/src/mongo/client/examples/mongoperf.vcxproj.filters @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <ItemGroup> + <ClCompile Include="mongoperf.cpp" /> + <ClCompile Include="..\mongo_client_lib.cpp"> + <Filter>shared files</Filter> + </ClCompile> + <ClCompile Include="..\..\util\mmap.cpp"> + <Filter>shared files</Filter> + </ClCompile> + <ClCompile Include="..\..\util\mmap_win.cpp"> + <Filter>shared files</Filter> + </ClCompile> + <ClCompile Include="..\..\util\logfile.cpp"> + <Filter>shared files</Filter> + </ClCompile> + </ItemGroup> + <ItemGroup> + <Filter Include="shared files"> + <UniqueIdentifier>{847e788b-8e8c-48de-829f-6876c9008440}</UniqueIdentifier> + </Filter> + <Filter Include="includes"> + <UniqueIdentifier>{d855a95e-71ad-4f54-ae1b-94e7aa894394}</UniqueIdentifier> + </Filter> + </ItemGroup> + <ItemGroup> + <ClInclude Include="..\..\bson\bson-inl.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\inline_decls.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bson.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bson_db.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsonelement.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsonmisc.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsonobj.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsonobjbuilder.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsonobjiterator.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\bsontypes.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\util\logfile.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\stringdata.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\oid.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\bson\ordering.h"> + <Filter>includes</Filter> + </ClInclude> + <ClInclude Include="..\..\util\mmap.h"> + <Filter>includes</Filter> + </ClInclude> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/src/mongo/client/examples/rs.cpp b/src/mongo/client/examples/rs.cpp new file mode 100644 index 00000000000..3307d87b56b --- /dev/null +++ b/src/mongo/client/examples/rs.cpp @@ -0,0 +1,118 @@ +// rs.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * example of using replica sets from c++ + */ + +#include "client/dbclient.h" +#include <iostream> +#include <vector> + +using namespace mongo; +using namespace std; + +void workerThread( string collName , bool print , DBClientReplicaSet * conn ) { + + while ( true ) { + try { + conn->update( collName , BSONObj() , BSON( "$inc" << BSON( "x" << 1 ) ) , true ); + + BSONObj x = conn->findOne( collName , BSONObj() ); + + if ( print ) { + cout << x << endl; + } + + BSONObj a = conn->slaveConn().findOne( collName , BSONObj() , 0 , QueryOption_SlaveOk ); + BSONObj b = conn->findOne( collName , BSONObj() , 0 , QueryOption_SlaveOk ); + + if ( print ) { + cout << "\t A " << a << endl; + cout << "\t B " << b << endl; + } + } + catch ( std::exception& e ) { + cout << "ERROR: " << e.what() << endl; + } + sleepmillis( 10 ); + } +} + +int main( int argc , const char ** argv ) { + + unsigned nThreads = 1; + bool print = false; + bool testTimeout = false; + + for ( int i=1; i<argc; i++ ) { + if ( mongoutils::str::equals( "--threads" , argv[i] ) ) { + nThreads = atoi( argv[++i] ); + } + else if ( mongoutils::str::equals( "--print" , argv[i] ) ) { + print = true; + } + // Run a special mode to demonstrate the DBClientReplicaSet so_timeout option. + else if ( mongoutils::str::equals( "--testTimeout" , argv[i] ) ) { + testTimeout = true; + } + else { + cerr << "unknown option: " << argv[i] << endl; + return 1; + } + + } + + string errmsg; + ConnectionString cs = ConnectionString::parse( "foo/127.0.0.1" , errmsg ); + if ( ! cs.isValid() ) { + cout << "error parsing url: " << errmsg << endl; + return 1; + } + + DBClientReplicaSet * conn = dynamic_cast<DBClientReplicaSet*>(cs.connect( errmsg, testTimeout ? 10 : 0 )); + if ( ! conn ) { + cout << "error connecting: " << errmsg << endl; + return 2; + } + + string collName = "test.rs1"; + + conn->dropCollection( collName ); + + if ( testTimeout ) { + conn->insert( collName, BSONObj() ); + try { + conn->count( collName, BSON( "$where" << "sleep(40000)" ) ); + } catch( DBException& ) { + return 0; + } + cout << "expected socket exception" << endl; + return 1; + } + + vector<boost::shared_ptr<boost::thread> > threads; + for ( unsigned i=0; i<nThreads; i++ ) { + string errmsg; + threads.push_back( boost::shared_ptr<boost::thread>( new boost::thread( boost::bind( workerThread , collName , print , (DBClientReplicaSet*)cs.connect(errmsg) ) ) ) ); + } + + for ( unsigned i=0; i<threads.size(); i++ ) { + threads[i]->join(); + } + +} diff --git a/src/mongo/client/examples/second.cpp b/src/mongo/client/examples/second.cpp new file mode 100644 index 00000000000..6cc2111580f --- /dev/null +++ b/src/mongo/client/examples/second.cpp @@ -0,0 +1,56 @@ +// second.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <iostream> + +#include "client/dbclient.h" + +using namespace std; +using namespace mongo; + +int main( int argc, const char **argv ) { + + const char *port = "27017"; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = argv[ 2 ]; + } + + DBClientConnection conn; + string errmsg; + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + + const char * ns = "test.second"; + + conn.remove( ns , BSONObj() ); + + conn.insert( ns , BSON( "name" << "eliot" << "num" << 17 ) ); + conn.insert( ns , BSON( "name" << "sara" << "num" << 24 ) ); + + auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() ); + cout << "using cursor" << endl; + while ( cursor->more() ) { + BSONObj obj = cursor->next(); + cout << "\t" << obj.jsonString() << endl; + } + + conn.ensureIndex( ns , BSON( "name" << 1 << "num" << -1 ) ); +} diff --git a/src/mongo/client/examples/simple_client_demo.vcxproj b/src/mongo/client/examples/simple_client_demo.vcxproj new file mode 100755 index 00000000000..358513f307a --- /dev/null +++ b/src/mongo/client/examples/simple_client_demo.vcxproj @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{89C30BC3-2874-4F2C-B4DA-EB04E9782236}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <RootNamespace>simple_client_demo</RootNamespace>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+
+ <PropertyGroup>
+ <ConfigurationType>Application</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <UseDebugLibraries>true</UseDebugLibraries>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <IncludePath>..\..;..\..\third_party\pcre-7.4;$(IncludePath)</IncludePath>
+ <LibraryPath>\boost\lib\vs2010_32;$(LibraryPath)</LibraryPath>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ </PropertyGroup>
+
+ <ItemDefinitionGroup>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>c:\boost;\boost</AdditionalIncludeDirectories>
+ </ClCompile>
+ </ItemDefinitionGroup>
+
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions> _CRT_SECURE_NO_WARNINGS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories>c:\boost;\boost</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <AdditionalDependencies>ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ </Link>
+ </ItemDefinitionGroup>
+
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions> _CRT_SECURE_NO_WARNINGS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+
+ </ClCompile>
+ <Link>
+ <SubSystem>Console</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ <AdditionalDependencies>ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ </Link>
+ </ItemDefinitionGroup>
+
+ <ItemGroup>
+ <ClCompile Include="..\mongo_client_lib.cpp" />
+ <ClCompile Include="..\simple_client_demo.cpp" />
+ </ItemGroup>
+
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+
+</Project>
\ No newline at end of file diff --git a/src/mongo/client/examples/simple_client_demo.vcxproj.filters b/src/mongo/client/examples/simple_client_demo.vcxproj.filters new file mode 100755 index 00000000000..8aa5a1a96c5 --- /dev/null +++ b/src/mongo/client/examples/simple_client_demo.vcxproj.filters @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+ <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="..\simple_client_demo.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="..\mongo_client_lib.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ </ItemGroup>
+</Project>
\ No newline at end of file diff --git a/src/mongo/client/examples/tail.cpp b/src/mongo/client/examples/tail.cpp new file mode 100644 index 00000000000..90e62d279c1 --- /dev/null +++ b/src/mongo/client/examples/tail.cpp @@ -0,0 +1,46 @@ +// tail.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* example of using a tailable cursor */ + +#include "../../client/dbclient.h" +#include "../../util/goodies.h" + +using namespace mongo; + +void tail(DBClientBase& conn, const char *ns) { + BSONElement lastId = minKey.firstElement(); + Query query = Query(); + + auto_ptr<DBClientCursor> c = + conn.query(ns, query, 0, 0, 0, QueryOption_CursorTailable); + + while( 1 ) { + if( !c->more() ) { + if( c->isDead() ) { + break; // we need to requery + } + + // all data (so far) exhausted, wait for more + sleepsecs(1); + continue; + } + BSONObj o = c->next(); + lastId = o["_id"]; + cout << o.toString() << endl; + } +} diff --git a/src/mongo/client/examples/tutorial.cpp b/src/mongo/client/examples/tutorial.cpp new file mode 100644 index 00000000000..aa5ad02b55d --- /dev/null +++ b/src/mongo/client/examples/tutorial.cpp @@ -0,0 +1,71 @@ +//tutorial.cpp + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <iostream> +#include "../../client/dbclient.h" + +// g++ tutorial.cpp -lmongoclient -lboost_thread -lboost_filesystem -o tutorial +// Might need a variant of the above compile line. This worked for me: +//g++ tutorial.cpp -L[mongo directory] -L/opt/local/lib -lmongoclient -lboost_thread-mt -lboost_filesystem -lboost_system -I/opt/local/include -o tutorial + +using namespace mongo; + +void printIfAge(DBClientConnection& c, int age) { + auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", QUERY( "age" << age ).sort("name") ); + while( cursor->more() ) { + BSONObj p = cursor->next(); + cout << p.getStringField("name") << endl; + } +} + +void run() { + DBClientConnection c; + c.connect("localhost"); //"192.168.58.1"); + cout << "connected ok" << endl; + BSONObj p = BSON( "name" << "Joe" << "age" << 33 ); + c.insert("tutorial.persons", p); + p = BSON( "name" << "Jane" << "age" << 40 ); + c.insert("tutorial.persons", p); + p = BSON( "name" << "Abe" << "age" << 33 ); + c.insert("tutorial.persons", p); + p = BSON( "name" << "Methuselah" << "age" << BSONNULL); + c.insert("tutorial.persons", p); + p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" ); + c.insert("tutorial.persons", p); + + c.ensureIndex("tutorial.persons", fromjson("{age:1}")); + + cout << "count:" << c.count("tutorial.persons") << endl; + + auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj()); + while( cursor->more() ) { + cout << cursor->next().toString() << endl; + } + + cout << "\nprintifage:\n"; + printIfAge(c, 33); +} + +int main() { + try { + run(); + } + catch( DBException &e ) { + cout << "caught " << e.what() << endl; + } + return 0; +} diff --git a/src/mongo/client/examples/whereExample.cpp b/src/mongo/client/examples/whereExample.cpp new file mode 100644 index 00000000000..12b68d7add3 --- /dev/null +++ b/src/mongo/client/examples/whereExample.cpp @@ -0,0 +1,69 @@ +// @file whereExample.cpp +// @see http://www.mongodb.org/display/DOCS/Server-side+Code+Execution + +/* Copyright 2009 10gen Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <iostream> + +#include "client/dbclient.h" + +using namespace std; +using namespace mongo; + +int main( int argc, const char **argv ) { + + const char *port = "27017"; + if ( argc != 1 ) { + if ( argc != 3 ) + throw -12; + port = argv[ 2 ]; + } + + DBClientConnection conn; + string errmsg; + if ( ! conn.connect( string( "127.0.0.1:" ) + port , errmsg ) ) { + cout << "couldn't connect : " << errmsg << endl; + throw -11; + } + + const char * ns = "test.where"; + + conn.remove( ns , BSONObj() ); + + conn.insert( ns , BSON( "name" << "eliot" << "num" << 17 ) ); + conn.insert( ns , BSON( "name" << "sara" << "num" << 24 ) ); + + auto_ptr<DBClientCursor> cursor = conn.query( ns , BSONObj() ); + + while ( cursor->more() ) { + BSONObj obj = cursor->next(); + cout << "\t" << obj.jsonString() << endl; + } + + cout << "now using $where" << endl; + + Query q = Query("{}").where("this.name == name" , BSON( "name" << "sara" )); + + cursor = conn.query( ns , q ); + + int num = 0; + while ( cursor->more() ) { + BSONObj obj = cursor->next(); + cout << "\t" << obj.jsonString() << endl; + num++; + } + MONGO_assert( num == 1 ); +} |