The following code sample illustrates working with the API
:::c++
#include <uma/bson/Element.h>
#include <uma/bson/Document.h>
#include <uma/bson/Undefined.h>
#include <uma/bson/Date.h>
#include <uma/bson/Null.h>
#include <uma/bson/RegularExpression.h>
#include <Poco/FileStream.h>
using uma::bson::Value;
using uma::bson::SharedElement;
using uma::bson::Document;
using uma::bson::Undefined;
using uma::bson::Date;
using uma::bson::Null;
using uma::bson::RegularExpression;
Document doc; // Use Document doc( 0 ) if you do not want automatically assigned ObjectId in new document
doc.set( "double", 1.0 );
doc.set( "string", "string value" );
doc.set( "undefined", Undefined() );
doc.set( "boolean", true );
doc.set( "date", Date() );
doc.set( "null", Null() );
doc.set( "regex", RegularExpression( "^abc", "$(1)" ) );
doc.set( "integer", 1 );
doc.set( "long", static_cast<int64_t>( 2 ) );
// BSON IO sample
const string out( "/tmp/doctest.bson" );
Poco::FileOutputStream fos( out, std::ios::out | std::ios::binary | std::ios::trunc );
doc.toBson( fos );
fos.close();
Document fromBson = Document::fromFile( out );
assert( doc.get( "double" )->getValue<Double>().getValue() == 1.0 );
assert( doc.get( "string" )->getValue<String>().getValue() == "string value" );
auto ufields = fromBson.getFieldNames();
for ( auto iter = fields.begin(); iter != fields.end(); ++iter )
{
SharedElement elem = fromBson.get( *iter );
switch ( elem->getType() )
{
case Value::Type::Double: double d = elem->getValue<Double>().getValue(); break;
default: break;
}
}
// JSON IO sample
const std::string out( "/tmp/doctest.json" );
Poco::FileOutputStream fos( out, std::ios::out | std::ios::binary | std::ios::trunc );
doc.toJson( fos, true );
fos.close();
Poco::FileInputStream fis( out );
Document fromJson = Document::fromJson( fis );