From 34de75445d87df5e29b2b1e77fee86613c88c6d1 Mon Sep 17 00:00:00 2001 From: Eliot Horowitz Date: Fri, 21 Jan 2011 12:58:20 -0500 Subject: [PATCH] some BSONObjBuilder helpers for accessing data whilebuilding --- bson/bson-inl.h | 28 ++++++++++++++++++++++++++++ bson/bsonobjbuilder.h | 5 +++++ 2 files changed, 33 insertions(+) diff --git a/bson/bson-inl.h b/bson/bson-inl.h index cf52747b886..5b4c490ea74 100644 --- a/bson/bson-inl.h +++ b/bson/bson-inl.h @@ -121,6 +121,26 @@ namespace mongo { return *this; } + /* add all the fields from the object specified to this object if they don't exist */ + inline BSONObjBuilder& BSONObjBuilder::appendElementsUnique(BSONObj x) { + set have; + { + BSONObjIterator i = iterator(); + while ( i.more() ) + have.insert( i.next().fieldName() ); + } + + BSONObjIterator it(x); + while ( it.more() ) { + BSONElement e = it.next(); + if ( have.count( e.fieldName() ) ) + continue; + append(e); + } + return *this; + } + + inline bool BSONObj::isValid() { int x = objsize(); return x > 0 && x <= BSONObjMaxInternalSize; @@ -205,6 +225,14 @@ namespace mongo { return BSONObjIterator( s , e ); } + inline bool BSONObjBuilder::hasField( const StringData& name ) const { + BSONObjIterator i = iterator(); + while ( i.more() ) + if ( strcmp( name.data() , i.next().fieldName() ) == 0 ) + return true; + return false; + } + /* WARNING: nested/dotted conversions are not 100% reversible * nested2dotted(dotted2nested({a.b: {c:1}})) -> {a.b.c: 1} * also, dotted2nested ignores order diff --git a/bson/bsonobjbuilder.h b/bson/bsonobjbuilder.h index dda89c8e6ce..a39b529b74c 100644 --- a/bson/bsonobjbuilder.h +++ b/bson/bsonobjbuilder.h @@ -104,6 +104,9 @@ namespace mongo { /** add all the fields from the object specified to this object */ BSONObjBuilder& appendElements(BSONObj x); + /** add all the fields from the object specified to this object if they don't exist already */ + BSONObjBuilder& appendElementsUnique( BSONObj x ); + /** append element to the object we are building */ BSONObjBuilder& append( const BSONElement& e) { assert( !e.eoo() ); // do not append eoo, that would corrupt us. the builder auto appends when done() is called. @@ -616,6 +619,8 @@ namespace mongo { BSONObjIterator iterator() const ; + bool hasField( const StringData& name ) const ; + int len() const { return _b.len(); } private: