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.
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 );