0

I have to convert this mongodb aggregate to spring aggregate code

{ $addFields: {
    "versions" : { $filter: {
        input: "$versions",
        as: "version",
        cond: {$in: ["$$version.parentId", "$libraries._id"]}
    }}
}}

My current code is

AddFieldsOperation.with("versions", 
    ArrayOperators.arrayOf("versions").filter().as("version").by(
        ArrayOperators.In.arrayOf("version.parentId").containsValue(
            ArrayOperators.arrayOf("libraries._id")
        )
    )
)

but this throws this error:

$in requires an array as a second argument, found: objectId'

I assume it's because it's not accepting the argument

ArrayOperators.arrayOf("libraries._id")
B. Fleming
  • 7,170
  • 1
  • 18
  • 36
Alex
  • 191
  • 1
  • 10

2 Answers2

1

If we take a look at the Spring documentation for ArrayOperators, we find the following method definition:

arrayOf

public static ArrayOperators.ArrayOperatorFactory arrayOf(String fieldReference)

Take the array referenced by given fieldReference.

Parameters:
    fieldReference - must not be null.
Returns:

Notice that it states that fieldReference should reference an "array". It seems likely that you want to change ArrayOperators.arrayOf("libraries._id") to ArrayOperators.arrayOf("libraries") instead.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36
  • This doesn't work, there is no fieldReference configured and I can't change that. The snippet ```{$in: ["$$version.parentId", "$libraries._id"]}``` works in mongo, but it's not correctly converted to spring – Alex Jun 06 '19 at 10:09
  • What do you mean by "there is no fieldReference configured"? I'm not familiar with Spring, but wouldn't `fieldReference` simply be a string that matches some array field on your document? Have you attempted the above? – B. Fleming Jun 06 '19 at 17:00
  • I thought you meant $ref, which I don't have. I have a fieldReference like you said, but the snippet doesn't work. I want to filter the versions array by checking if versions.parentId is in libraries._id – Alex Jun 10 '19 at 05:59
1

I had query like

{
   coupons: {
      $filter: {
         input: "$coupons",
         as: "coupon",
         cond: { 
             $in: [ "$$coupon._id", ["ABC", "DEF"] ]
         }
      }
   }
}

Below solution worked for me

filter("$coupons").as("coupon").by(ArrayOperators.In.arrayOf(couponIds).containsValue("$$coupon._id"))

Note: couponIds is List with values ["ABC", "DEF"]

letsDoThis
  • 71
  • 1
  • 7