0

次の MongoDB シェルコードをエミュレートしようとしています。

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 を使用すると、自分が思っていたものを完全に複製していないというヒントが得られた可能性もあります。

シェルで見ていた 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 に答える