mongoc:不要让$ unwind与mongoDB c驱动程序一起工作

时间:2015-08-19 13:18:23

标签: mongodb mongo-c-driver

我有这样的文档使用子文档数组“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并且它有效。如何使用bson_append _ ???正确插入$ unwind

bson_t *pipeline;

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

1 个答案:

答案 0 :(得分:0)

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

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的这个方面。