简体   繁体   中英

How to find number of occurrence of searched string in mongodb aggregation?

I want to find count or number of occurrence in string by using mongodb aggregation. These is my array of object:-

[
  {
    text:'Dummy Lorem Ipsum',
    name:'Alex'
  },
  {
    text:'Other dummy dummy Data dummy',
    name:'John'
  },
  {
    text:'Another dummy dummy data',
    name:'Abraham'
  },
  {
    text:'Last dummy one dummy data dummy',
    name:'Bethny'
  },
  {
    text:'Andrew has no data to display',
    name:'Andrew'
  },
];

If I searched for 'dummy' as searched string then I want output like this using mongodb aggregation:-

  {
    text:'Dummy Lorem Ipsum',
    name:'Alex',
    count:1
  },
  {
    text:'Other dummy dummy Data dummy',
    name:'John',
    count:3
  },
  {
    text:'Another dummy dummy data',
    name:'Abraham',
    count:2
  },
  {
    text:'Last dummy one dummy data dummy',
    name:'Bethny',
    count:3
  },
  {
    text:'Andrew has no data to display',
    name:'Andrew',
    count:0
  },
];

Please guide me to solve this issue by making proper aggregation query as soon as possible. Thanks in advance.

If you're using MongoDB 4.2+, you can use $size with $regexFindAll to get your count:

YourModel.aggregate([
  {
    "$addFields": {
      "count": {
        $size: { 
          $regexFindAll: { input: "$text", regex: /dummy/, options: 'i' }  }
        }
    }
  }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM