0

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

db.collection.find( { $and: [ { $or: [ { document: { field: "X" } }, { field: "X" } ] }, { _id: ObjectId("X") } ] } );

这是我尝试过的(使用新的 MongoDB-C-Driver):

  bson_init(&query);
  bson_append_document_begin(&query, "$and", 4, &and);
  bson_append_oid(&and, "_id", 3, oid);
     bson_append_document_begin(&and, "$or", 3, &or);
     bson_append_utf8(&query, "field", 5, "X", 1);
     bson_append_document_end(&and, &or);

     bson_append_document_begin(&and, "$or", 3, &or);
     bson_append_utf8(&query, "document.field", 14, "X", 1);
     bson_append_document_end(&and, &or);
  bson_append_document_end(&query, &and);
  collection = mongoc_client_get_collection (client, "db", "collection");
  cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0, &query, NULL, NULL);
  if(mongoc_cursor_next(cursor, &doc)){
     printf("> Field found\r\n");
  }

先感谢您。

此致。

4

1 回答 1

2

用于创建嵌套文档的 libbson 命令式 API 有点棘手,不幸的是,您偶然发现了一个简单的陷阱。一旦使用 bson_append_document_begin 或 bson_append_array_begin 打开了子文档,在执行了相应的 _end() 调用之前,您不得对其进行写入。在这种情况下,您在写入“查询”的“或”文档中有 append_utf8() 调用。

要获得更简单的 bson 组合方法,请考虑使用 BCON api,它以最小的开销提供更具声明性的语法:

BCON_APPEND(&other_query,
    "$and", "{",
        "_id", BCON_OID(&oid),
        "$or", "{",
            "field", "X",
        "}",
        "$or", "{",
            "document.field", "X",
        "}",
    "}");

使用 bcon api 也可能给您一个提示,即您并没有完全复制您的想法。

要生成您在 shell 中查看的 bson:

BCON_APPEND(&correct_query,
    "$and",
    "[",
        "{", "$or", "[",
            "{", "document", "{", "field", "X", "}", "}",
            "{", "field", "X", "}",
        "]", "}",
        "{", "_id", BCON_OID(&oid), "}",
    "]"
);

您还可以使用 bson_as_json() 函数将 bson 文档字符串化为 json,这样可以更轻松地查看您构建的对象

iterative: { "$and" : { "_id" : { "$oid" : "53ff00f4342d8c1c712b4841" }, "$or" : { "field" : "X" }, "$or" : { "document.field" : "X" } } }
bcon: { "$and" : { "_id" : { "$oid" : "53ff00f4342d8c1c712b4841" }, "$or" : { "field" : "X" }, "$or" : { "document.field" : "X" } } }
correct: { "$and" : [ { "$or" : [ { "document" : { "field" : "X" } }, { "field" : "X" } ] }, { "_id" : { "$oid" : "53ff00f4342d8c1c712b4841" } } ] }

相关文档:http ://api.mongodb.org/libbson/current/

于 2014-08-28T14:20:22.197 回答