mirror of
https://github.com/mongodb/mongo.git
synced 2024-12-01 09:32:32 +01:00
77 lines
2.1 KiB
C++
77 lines
2.1 KiB
C++
/** @file bsondemo.cpp */
|
|
|
|
#include "../bson.h"
|
|
#include <iostream>
|
|
#include <vector>
|
|
|
|
using namespace std;
|
|
using namespace bson;
|
|
|
|
int main()
|
|
{
|
|
cout << "build bits: " << 8 * sizeof(char *) << endl;
|
|
|
|
/* a bson object defaults on construction to { } */
|
|
bo empty;
|
|
cout << "empty: " << empty << endl;
|
|
|
|
/* make a simple { name : 'joe', age : 33.7 } object */
|
|
{
|
|
bob b;
|
|
b.append("name", "joe");
|
|
b.append("age", 33.7);
|
|
b.obj();
|
|
}
|
|
|
|
/* make { name : 'joe', age : 33.7 } with a more compact notation. */
|
|
bo x = bob().append("name", "joe").append("age", 33.7).obj();
|
|
|
|
/* convert from bson to json */
|
|
string json = x;
|
|
cout << "json for x:" << json << endl;
|
|
|
|
/* access some fields of bson object x */
|
|
cout << "Some x things: " << x["name"] << ' ' << x["age"].Number() << ' ' << x.isEmpty() << endl;
|
|
|
|
/* make a bit more complex object with some nesting
|
|
{ x : 'asdf', y : true, subobj : { z : 3, q : 4 } }
|
|
*/
|
|
bo y = BSON( "x" << "asdf" << "y" << true << "subobj" << BSON( "z" << 3 << "q" << 4 ) );
|
|
|
|
/* print it */
|
|
cout << "y: " << y << endl;
|
|
|
|
/* reach in and get subobj.z */
|
|
cout << "subobj.z: " << y.getFieldDotted("subobj.z").Number() << endl;
|
|
|
|
/* alternate syntax: */
|
|
cout << "subobj.z: " << y["subobj"]["z"].Number() << endl;
|
|
|
|
/* fetch all *top level* elements from object y into a vector */
|
|
vector<be> v;
|
|
y.elems(v);
|
|
cout << v[0] << endl;
|
|
|
|
/* into an array */
|
|
list<be> L;
|
|
y.elems(L);
|
|
|
|
bo sub = y["subobj"].Obj();
|
|
|
|
/* grab all the int's that were in subobj. if it had elements that were not ints, we throw an exception
|
|
(capital V on Vals() means exception if wrong type found
|
|
*/
|
|
vector<int> myints;
|
|
sub.Vals(myints);
|
|
cout << "my ints: " << myints[0] << ' ' << myints[1] << endl;
|
|
|
|
/* grab all the string values from x. if the field isn't of string type, just skip it --
|
|
lowercase v on vals() indicates skip don't throw.
|
|
*/
|
|
vector<string> strs;
|
|
x.vals(strs);
|
|
cout << strs.size() << " strings, first one: " << strs[0] << endl;
|
|
|
|
return 0;
|
|
}
|