Search code examples
javamongodbaggregation-frameworkmongodb-java

How to use $toLower and $trim aggregation operators using MongoDB Java?


I have a collection called Users, which contains an array called skills.

I use the following code to unwind the skills array and count the number of documents associated with each skill:

Bson uw = unwind("$skills");
Bson sbc = sortByCount("$skills");
Bson limit = limit(10);
coll.aggregate(Arrays.asList(uw, sbc,limit)).forEach(printDocuments());

Now I want to make use of $trim and $toLower operations for the above aggregation because in the database, some skills saved in different ways (e.g., "CSS", "CSS ", and "css").

I'm able to do this in the mongo shell with the following aggregation:

db.users.aggregate([{$unwind:"$skills"} , {$sortByCount:{$toLower:{$trim:{input:"$skills"}}}}])

But I'm having troubles with implementing it in Java.

Do you have any idea?


Solution

  • I managed to find a way to do this with changing the sortByCount to the following:

    Bson sbc = sortByCount(eq("$toLower", eq("$trim", eq("input", "$skills"))));