【问题标题】:Mongo DB query - Aggregation $cond if condition implementation in c++ codeMongo DB 查询 - 如果条件实现在 C++ 代码中的聚合 $cond
【发布时间】:2018-08-03 06:58:06
【问题描述】:

我有一个如下的 mongo DB 查询

db.getCollection('ABC_COLLECTION_01').aggregate ([{ "$group" : { "_id" : 0, "total" : { "$sum" : "$columA" }, "total_sub" : { "$sum" : {$cond:{ if: { $gte: [ "$columnB", new ISODate("2018-01-01T04:58:09.000+0100") ] }, then: "$columA", else: 0 }}} }}])

此查询运行良好。如果我在 ABC_COLLECTION_01 上运行它,它将返回类似的结果(仅作为示例)

total = 250 & total_sub = 120

现在我必须使用 mongo::BSONArrayBuilder 在 C++ 代码中编写此查询,如下所示

//Calculate 2 sum
aBuilder.append(BSON("$group"<<BSON("_id"<<0
                                        <<"total"<<BSON("$sum"<<'$' +columA)
                                        <<"total_sub"<<BSON("$sum"<<'$cond'<<'if'<<'$' +columB<<"$gte"<<rmsmongo::utils::Adaptor::ToMongoDate(StartTime,true)<<'then'<<'$' +columA<<'else'<<0))));
mongo::BSONArray New_AggregationQuery = aBuilder.arr();
std::auto_ptr<dsclient::Cursor> Cursor = _MyCollection.aggregate(New_AggregationQuery, dsclient::Option_aggregate().retry(dsclient::Retry(dsclient::ExponentialRetry, 2)).maxTimeMS(200000));

如果您看到我为 $total_sub 编写的 $cond 在 C++ 代码中是错误的 - 它不起作用。 你能帮我纠正一下吗? 提前致谢

【问题讨论】:

    标签: c++ mongodb mongodb-query bson


    【解决方案1】:

    请注意,您在此处使用的旧版 C++ 驱动程序已停产。我不能强烈推荐您立即切换到新的 mongocxx 驱动程序,该驱动程序位于同一 repo 的 master 分支上。它提供了显着的优势,其中最重要的是它得到了积极的维护。

    也就是说,如果您仔细观察,您会发现您的工作查询中的 if 表达式有一个子文档,但在您的 C++ 代码中,您并没有开始一个新的 BSON 子文档。可能还有其他错误。

    说真的,我真的建议您停止处理此问题并迁移到新驱动程序。旧版驱动程序(或者您甚至使用 26compat)中的任何错误或不符合项将永远不会得到修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多