简体   繁体   English

Mongo DB查询-如果条件在C ++代码中实现,则聚合$ cond

[英]Mongo DB query - Aggregation $cond if condition implementation in c++ code

I have a mongo DB query as below 我有一个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 }}} }}])

This query is working fine. 此查询工作正常。 If I run this on ABC_COLLECTION_01, it will return result like (just for an example) 如果我在ABC_COLLECTION_01上运行它,它将返回类似的结果(仅作为示例)

total = 250 & total_sub = 120 总计= 250&total_sub = 120

Now I have to write this query in C++ code using mongo::BSONArrayBuilder as below 现在,我必须使用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));

If you see the $cond I have written for $total_sub is wrong in C++ code- it is not working. 如果您看到我为$ total_sub编写的$ cond在C ++代码中是错误的-它不起作用。 Can you please help me to get it corrected? 您能帮我纠正一下吗? Thanks in advance 提前致谢

Please note that the legacy C++ driver which you appear to be using here is end-of-life. 请注意,您似乎在此处使用的旧版C ++驱动程序已停产。 I cannot recommend strongly enough that you immediately switch to the new mongocxx driver, found on the master branch of the same repo. 我不能强烈建议您立即切换到同一仓库的master分支上找到的新mongocxx驱动程序。 It offers significant advantages, not the least of which is that it is actively maintained. 它具有显着的优势,尤其重要的是它得到了积极维护。

That said, if you look closely, you can see that the if expression in your working query has a subdocument, but in your C++ code, you aren't starting a new BSON subdocument. 就是说,如果仔细观察,您会发现工作查询中的if表达式有一个子文档,但是在C ++代码中,您不会启动新的BSON子文档。 There are probably other errors. 可能还有其他错误。

Seriously though, I really recommend you stop working on this and get migrated to the new driver. 认真地说,我真的建议您停止这项工作,并迁移到新驱动程序。 Any bugs or non-conformances in the legacy driver (or are you even using 26compat) will never be fixed. 旧版驱动程序中的任何错误或不符合项(或者甚至使用26compat)都将永远不会得到修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM