0

I have mongodb Database and I have this document structure :

   {
     "_id": ObjectId("2145214545ffff"),
     "arr":[a , b , c , d , e , f , g , h , i, j]
   }

I want to execute aggregation pipeline , which gives me this result:

 {
         "_id": ObjectId("2145214545ffff"),
         "arr":[a , d , g , j ]
       }

So what i need is kind of filtering on the array's items , which give me the 1st , 4th , 7th and so on items. Thx in advanced

1
  • What have you tried so far? Commented Jun 4, 2020 at 18:58

1 Answer 1

1

You need to use $map and $range operators.

The following query will be helpful:

db.collection.aggregate([
  {
    $project: {
      arr: {
        $map: {
          input: {
            $range: [
              0,
              {
                $size: "$arr"
              },
              3
            ]
          },
          as: "a",
          in: {
            $arrayElemAt: [
              "$arr",
              "$$a"
            ]
          }
        }
      }
    }
  }
])

MongoPlayGroundLink

Sign up to request clarification or add additional context in comments.

2 Comments

Hey @MoOmar, was this helpful?
Hey @ngShravil.py , this was nice,Thank you very much. Also The performance is great. I used reduce operator , it was working but slower. So map operator is nice for this use case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.