Home > Enterprise >  Mongodb Aggregate - How can i filter an array by multilpe array indexes?
Mongodb Aggregate - How can i filter an array by multilpe array indexes?

Time:11-17

I have a huge array and I need to get only array indexes that are multiple by 12. I thought using $filter, but I'm struggling in the cond parameter.

I'm using aggregate because there is more stuff that i need to do, but I'm stuck in this filter part.

data : [3,4,5,6,...,etc, <more 5000 items> ]

query:

db.test.aggregate([{$project:{filtered_values: {$filter:{input: '$data', as:data ,cond: { ??? some witchcraft ???}  }}}}])

Expected result:

[data[0],data[12],data[24],data[36],data[i%12 ===0]]

How can i reach this result with aggregate? Or if is $filter the best solution?

CodePudding user response:

Try this:

db.collection.aggregate([
   {
      $set: {
         data: {
            $map: {
               input: { $range: [0, { $size: "$data" }, 12] },
               as: "i",
               in: { $arrayElemAt: ["$data", "$$i"] }
            }
         }
      }
   }
])
  • Related