我正在尝试模拟以下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 );
但它似乎没有按预期工作。我还尝试用数组替换对象,然后在对象中嵌套数组,但无济于事。
答案 0 :(得分: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 );
答案 1 :(得分: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 );
然而,看the docs,我找不到建立“对象数组”的例子。因此,如果这不起作用,您可能需要联系驱动程序作者或MongoDB Google Groups。