Rmongodb $ cond in aggregation structure

I am trying to execute an amount in an operation group in rmongodb. The โ€œcolumnโ€ that I am summing up contains NaN values, so my sum returns NaN. I want to use $ project to replace NaN with zeros before running a group on command, but I'm stuck.

This will lead to the creation of dummy data (in the mongo console):

db.NAtest.insert({ y : 1, x : 1}) db.NAtest.insert({ y : 1, x : 2}) db.NAtest.insert({ y : 2, x : 3}) db.NAtest.insert({ y : 2, x : 4}) db.NAtest.insert({ y : 2, x : NaN}) 

This will produce the desired result (in the mongo console):

 db.NAtest.aggregate( { $project : { y : 1, x : { $cond : [ { $ne : ['$x', NaN] }, '$x', 0] } } } ) 

This is what I work in R:

 library(rmongodb) mongo <- mongo.create() buf <- mongo.bson.buffer.create() mongo.bson.buffer.append(buf, "aggregate", "NAtest"); mongo.bson.buffer.start.array(buf, "pipeline") mongo.bson.buffer.append.bson(buf, "0", mongo.bson.from.list(list('$project' = list(y = 1, x= 1)))) mongo.bson.buffer.finish.object(buf) cmd <- mongo.bson.from.buffer(buf) result <- mongo.command(mongo, "rmdb", cmd) 

When I try to add $ cond for NaN conversion using the following:

 x = list("$cond" = c(list("$ne" = c("$x", as.numeric(NA))), "$x", "0")) 

instead

 x = 1 

Results are not returned, and mongo.get.err () returns a value of 10, indicating that BSON is invalid.

If I start printing (cmd) in an R session when the $ cond option is enabled, the following output is output:

 > print(cmd) aggregate : 2 NAtest pipeline : 4 0 : 3 $project : 3 y : 1 1.000000 x : 3 $cond : 3 $ne : 4 0 : 2 $x 1 : 2 NA : 2 $x : 2 0 

I donโ€™t think the problem is with the NaN / as.numeric (NA) part of the code, because when I try to replace the word "number 2" with zero, I get the same error.

Thanks in advance.

+4
source share
1 answer

Rmongodb seems to be unable to cope with statements built into another statement during aggregation. I encountered the same problem when using $substr in $group .

Try using only one statement per step. If this is not possible, I can recommend the RMongo package as an alternative.

 dbAggregate( mongo, "db", '{ $project : { y : 1, x : {$cond : [{ $ne : ['$x', NaN] }, '$x', 0]} } }') 
0
source

Source: https://habr.com/ru/post/1491010/


All Articles