1

I have a variable roomsCount which is a filter for UI list of projects by amount of rooms. In the database, projects have value rooms which is an array, and store all data about them. This function sorts them, but here I also need to exclude projects where are no rooms or that field doesn't exist. I have found a way how to do it if there is not an aggregation, but how to avoid them in the pipeline?

  async aggregateAll(page, pageSize, filters, sortBy) {
    const options = {
      query: new FiltersQuery(filters),
      select: this.getAttributes(),
      sort: this.parseSortBy(sortBy),
      skip: (page - 1) * pageSize,
      limit: pageSize,
    };

    const query = this.projectModel.aggregate([
      { $match: options.query },
      {
        $addFields: { roomsCount: { $size: { $ifNull: ['$rooms', []] } } },
      },
      { $sort: { roomsCount: -1 } },
      { $skip: options.skip },
      { $limit: options.limit },
      { $project: options.select },
    ]); 

1 Answer 1

1

I think you should split the query.

First, check if field room exists with $exists.

$match: {room:{$exists:true}}

Then check the size, I think for check the size you will need to use $addFields, because with $size you can't use $gt.

$addFields: { roomSize: {$size:"$room"}},
$match: {roomSize:{$gt:0}}
Sign up to request clarification or add additional context in comments.

2 Comments

May I add several $match in an aggregate query?
yes, you should remove your $addFields, and add my "solution"

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.