4800

how to use spel to represent $cond of mongo

Question:

I have a collection with documents like below

{ "_id" : ObjectId("5946360fdab24b1d05fac7e6"), "name" : "aaa", "createdAt" : NumberLong("1497773583563"), "segmentedStatus" : 0 }

I want to stat how many documents with segmentedStatus = 1,

db.foo.aggregate( {$project: {_id:0, segmentedCount:{$cond: [{$eq:["$segmentedStatus",1]}, 1, 0]} } }, {$group: {_id:null, count:{$sum:"$segmentedCount"}}} )

In spring data mongo

Aggregation aggregation = newAggregation(project().and("segmentedCount").applyCondition(when(where("segmentedStatus").is(1)).then(1).otherwise(0)), group().sum("segmentedCount").as("count") );

but I feel above manner a little cumbersome so want to know if could use spel in this case , I tried below manner

Aggregation aggregation = newAggregation(project().andExpression("segmentedStatus == 1 ? 1 : 0").as("segmentedCount"), group().sum("segmentedCount").as("count") );

but it throws exception

Exception in thread "main" java.lang.IllegalArgumentException: Unsupported Element: org.springframework.data.mongodb.core.spel.ExpressionNode@4d5d943d Type: class org.springframework.data.mongodb.core.spel.ExpressionNode You probably have a syntax error in your SpEL expression!

Answer1:

The short hand ternary operator syntax for $cond is currently not supported. Still you can reference the $cond operator via cond(if, then, else)

<pre class="lang-java prettyprint-override">project() .and(AggregationSpELExpression.expressionOf("cond(segmentedStatus == 1, 1, 0)")) .grou...

which will create the following:

{ "$cond" : { "if" : { "$eq" : ["$segmentedStatus", 1] }, "then" : 1, "else" : 0 } }

Recommend

  • Group By and add columns
  • Java Caching frameworks for maintaining huge data
  • Newtonsoft inline formatting for subelement while serializing
  • Why is RAM in powers of 2?
  • Can't figure out a function to return a reference to a given type stored in RefCell
  • Visual basic auto imports namespaces
  • Meteor oplog for Mongo 2.6
  • set operation within a list column
  • How to get list of users who's birthday is today in MongoDB
  • WPF Listbox commands
  • Why does Apple use assign rather than weak to store a delegate?
  • MongoDB GeoJSON “Can't extract geo keys from object, malformed geometry?” when inserting type P
  • Mongodb update() vs. findAndModify() performace
  • Create registry key in 32-bit hive on x64 PC using Installshield 2012 LE - Avoid redirection
  • Configuring multiple DefaultJmslistenercontainerfactory
  • How to concat Pandas dataframe columns
  • vectorized indexing/slicing in numpy/scipy?
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • JPA flush vs commit
  • Approximate Order-Preserving Huffman Code
  • Using Sax parsing to edit and write XML in VB6
  • What is the purpose of TaskExecutor in spring?
  • Not able to aggregate on nested fields in elasticsearch
  • Grails calculated field in SQL
  • Django: Count of Group Elements
  • Linq Objects Group By & Sum
  • Read text file and split every line in MSBuild
  • Is possible to count alias result on mysql
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • Sending data from AppleScript to FileMaker records
  • MySQL WHERE-condition in procedure ignored
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • embed rChart in Markdown
  • LevelDB C iterator
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app