1

我有这样的文档,使用一组子文档“c”。

   {
      "_id" : 1,
      "c" : [
        {
          "p" : {
            "name" : "SimpleGroup"
          }
        },
        {
          "p" : {
            "name" : "SimpleGroup2"
          }
        }
      ]
    }

跑步

db.collection.aggregate([ { "$unwind" : "$c" }, { "$project" : { "name" : "$c.p.name" } } ])

在命令行中工作正常。如果我使用 mongoc 驱动程序构建相同的管道,它看起来像 $unwind 条目被忽略。

#include <bson.h>
#include <mongoc.h>

bson_t pipeline; bson_init(&pipeline);
bson_t pipeArr, pipeElem1, pipeElem2;
bson_append_array_begin(&pipeline, "pipeline", -1, &pipeArr);

bson_append_document_begin(&pipeArr, "0", -1, &pipeElem1);
bson_append_utf8(&pipeElem1, "$unwind", -1, "$c", -1);
bson_append_document_end(&pipeArr, &pipeElem1);

bson_append_document_begin(&pipeArr, "0", -1, &pipeElem1);
bson_append_document_begin(&pipeElem1, "$project", -1, &pipeElem2);
bson_append_utf8(&pipeElem2, "name", -1, "$c.p.name", -1);
bson_append_document_end(&pipeElem1, &pipeElem2);
bson_append_document_end(&pipeArr, &pipeElem1);

bson_append_array_end(&pipeline, &pipeArr);

cursor = mongoc_collection_aggregate (coll, MONGOC_QUERY_NONE, &pipeline, nullptr, nullptr);

做错了什么?

预期结果:

{ "_id" : 1, "name" : "SimpleGroup" }
{ "_id" : 1, "name" : "SimpleGroup2" }

检索结果:

{ "_id" : 1, "name" : [ "SimpleGroup", "SimpleGroup2" ] }

额外的

我尝试使用 BCON_NEW 并且它有效。$unwind 如何使用 bson_append_ 正确插入???.

bson_t *pipeline;

pipeline = BCON_NEW ("pipeline", "[",
  "{", "$unwind", "$c", "}",
  "{", "$project", "{", "name", "$c.p.name", "}", "}",
  "]");
4

1 回答 1

0

问题是管道阵列的创建。每个数组元素都有一个键,但我总是插入“0”,这会导致覆盖。

bson_t pipeline; bson_init(&pipeline);
bson_t pipeArr, pipeElem1, pipeElem2;
bson_append_array_begin(&pipeline, "pipeline", -1, &pipeArr);

bson_append_document_begin(&pipeArr, "0", -1, &pipeElem1);
bson_append_utf8(&pipeElem1, "$unwind", -1, "$c", -1);
bson_append_document_end(&pipeArr, &pipeElem1);

bson_append_document_begin(&pipeArr, "1", -1, &pipeElem1);
bson_append_document_begin(&pipeElem1, "$project", -1, &pipeElem2);
bson_append_utf8(&pipeElem2, "name", -1, "$c.p.name", -1);
bson_append_document_end(&pipeElem1, &pipeElem2);
bson_append_document_end(&pipeArr, &pipeElem1);

bson_append_array_end(&pipeline, &pipeArr);

在 bson_append_array_begin 之后,我错过了 bson_append_document_begin 的这一方面。

于 2015-08-24T12:34:21.713 回答