Frage

I'm trying to emulate the following MongoDB shellcode:

db.products.find( { $or : [ { title : /blue/i }, { tags : /blue/i } ] }, {_id:0, title:1} );

This is what I've tried:

bson query[1];
mongo_cursor cursor[1];

bson_init( query );

{
bson_append_start_object( query, "$or");
bson_append_regex( query, "title", "blue", "i" );
bson_append_regex( query, "tags", "blue", "i" );
bson_append_finish_object( query );
}

bson_finish( query );

mongo_cursor_init( cursor, conn, "test.products" );
mongo_cursor_set_query( cursor, query );

while( mongo_cursor_next( cursor ) == MONGO_OK ) {
  bson_iterator iterator[1];
  if ( bson_find( iterator, mongo_cursor_bson( cursor ), "title" )) {
      printf( "%s\n", bson_iterator_string( iterator ) );
  }
}

bson_destroy( query );
mongo_cursor_destroy( cursor );

But it does not seem to work as expected. I also tried to replace the object with an array and then nested the array within the object, but to no avail.

War es hilfreich?

Lösung

mongo_db answer

Ok, I've found the solution on this website:

https://groups.google.com/group/mongodb-user/browse_thread/thread/02a239b0bda84b82

Here's what I had to change:

bson_append_start_object( query, "$or");
bson_append_regex( query, "title", "blue", "i" );
bson_append_regex( query, "tags", "blue", "i" );
bson_append_finish_object( query );

should be

bson_append_start_array( query, "$or" );
    bson_append_start_object( query, "0"); 
        bson_append_regex( query, "title", "blue", "i" );
    bson_append_finish_object( query );     
    bson_append_start_object( query, "1"); 
        bson_append_regex( query, "tags", "blue", "i" );
    bson_append_finish_object( query );
bson_append_finish_array( query );

Andere Tipps

I am not really experienced with the C driver, but it looks like something is incorrect with your basic query structure.

The order should be something like this:

array => add Object {title:/blue/i} to array
      => add Object {tags:/blue/i} to array
finish array

So the code should be something like this:

bson_init(query);

bson_append_start_array( query, "$or" );
  bson_append_regex( query, "title", "blue", "i" );
  bson_append_regex( query, "tags", "blue", "i" );
bson_append_finish_array( query );

However, looking at the docs, I cannot find an example of building an "array of objects". So if this doesn't work, you may need to contact the driver author or the MongoDB Google Groups.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top