potato
potato

Reputation: 223

How to use $slice and project specific fields together in MongoDB aggregation?

https://mongoplayground.net/p/U2vvNZHIbfq

I created the situation to the above link, you can simply hit the run button Now I can set slice to 2, to make sure to project the first two item in "cars" only.

However, I don't know how to apply projecting specific fields only with "slice".

I want to project the "name" and "views" in the "cars" array only.

Upvotes: 1

Views: 630

Answers (1)

turivishal
turivishal

Reputation: 36104

You can add another project to hide unused fields,

  // you pipeline stages
  {
    $project: {
      "cars._id": 0,
      "cars.categoryId": 0,
      "cars.description": 0
    }
  }

Playground


Second way using $map in same stage,

  • $map to iterate loop of array that slice from cars array, return name and views fields
  // you pipeline stages
  {
    $project: {
      _id: 1,
      categoryName: 1,
      cars: {
        $map: {
          input: { $slice: ["$cars", 2] },
          in: {
            name: "$$this.name",
            views: "$$this.views"
          }
        }
      }
    }
  }

Playground

Upvotes: 2

Related Questions