regex as $filter in projection

前端 未结 3 1223
我寻月下人不归
我寻月下人不归 2020-12-20 20:16

I\'m trying to find (using a regexp) an array field and returns that element only

This is my data

  [
 {
\"_id\": \"56d6e8bbf7404bd80a017edb\",
\"nam         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 21:02

    This is how I solved it. If the query can be parsed to regex the projection is not added to aggregation, but happening after the db request. If the query string is normal string, the projection added.

    const { query } = req;  // /rea/ or 'C area3'
    
    const convertIfRegex = string => {
      const parts = string.split('/')
      let regex = string;
      let options = '';
    
      if (parts.length > 1) {
        regex = parts[1];
        options = parts[2];
      } else {
        return false
      }
    
      try {
        return new RegExp(regex, options);
      } catch (e) {
        return null
      }
    };
    
    const regex = convertIfRegex(queryString);
    const aggregations = [{ $match: { tags:query } }]
    
    if (!regex) {
      aggregations.push({
        $project: {
          tags: {$filter: {
            input: 'tags',
            as: 'item',
            cond: {$eq: ['$$item', query]}
          }}
        }
      })
    }
    
    let result = await caseNote.aggregate(aggregations);
    
    if (regex) {
      result = result.reduce((acc, entry) => {
        const tags = entry.tags.filter(({ tag }) => (
          tag.match(regex)
        ))
        if (tags.length) return [...acc, { ...entry, tags }];
        return acc;
      })
    }
    
    res.json(result)
    
    

提交回复
热议问题