Frage

Windows 7 64 SP1 -- MongoDB 2.2.0-rc2 -- Boost 1.42 -- MS VS 2010 Ultimate -- C++ driver

I have a function that takes a Query object as a parameter:

    someFunction( Query qu )

Advantages:

  1. Can accept either a Query object or a well-formed BSONObj.
  2. Have access to Query helpers such as sort/hint/etc.

Disadvantage:

  1. Can't do a server-side count (vs. a client-side count of a batch of results) akin to the shell's:

    nstudents = db.students.find({'address.state' : 'CA'}).count();
    

    i.e.,

    unsigned long long n = c.count("mydb.users", qu);
    

    raises the error:

    cannot convert ... from 'mongo::Query' to 'const mongo::BSONObj &
    

So, it was suggested I use a BSONObj as a parameter:

    someFunction ( BSONObj qu )

Advantages:

  1. Can do a server side count.
  2. Can convert to a Query and hence use its helpers.

Disadvantage:

  1. Anyone using the function must be aware not to pass a query as a Query object which is counter-intuitive.

So, my questions are:

Why aren't the helper methods of the Query class implemented in BSONObj? Or, conversely, why couldn't a server-side count method be implemented with the Query class?

War es hilfreich?

Lösung

unsigned long long count (const string &ns, const BSONObj &query=BSONObj(),
int options=0)

So, count should receive BSONObj (or Base/Derived of/from BSONObj).

Query has implicit c-tor, that receives BSONObj.

Query (const BSONObj &b)

Query has public member obj, that is BSONObj.

Your function can be

// i think const Query& qu will be better.
someFunction( Query qu )

and for call count you should use

c.count("mydb.users", qu.obj);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top