1

我正在尝试模拟以下 MongoDB shellcode:

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

这是我尝试过的:

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

但它似乎没有按预期工作。我还尝试用数组替换对象,然后将数组嵌套在对象中,但无济于事。

4

2 回答 2

3

mongo_db 答案

好的,我在这个网站上找到了解决方案:

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

这是我必须改变的:

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_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 );
于 2012-05-05T10:39:18.623 回答
0

我对 C 驱动程序并没有真正的经验,但是您的基本查询结构看起来有些不正确。

顺序应该是这样的:

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

所以代码应该是这样的:

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

但是,查看文档,我找不到构建“对象数组”的示例。因此,如果这不起作用,您可能需要联系驱动程序作者或 MongoDB Google Groups。

于 2012-05-04T18:31:17.183 回答