How to Count Matched array elements

瘦欲@ 提交于 2019-12-06 11:18:17

The $in operator just "queries" documents that contain one of the possible values, so it does not remove anything from the array.

If you want to count "only matches" then apply $setIntersection to the array before $size:

db.movies.aggregate([
  {
    $match: { countries: { $in: ["USA", 'China', 'Australia'] } }
  },
  {
    $project: {
      countries: {
        $size: { 
         "$setIntersection": [["USA", 'China', 'Australia'], '$countries' ] 
       }
    }
  }
]);

That returns the "set" of "unique" matches to the array provided against the array in the document.

There is an alternate of $in as an aggregation operator in modern releases ( MongoDB 3.4 at least ). This works a bit differently in "testing" a "singular" value against an array of values. In array comparison you would apply with $filter:

db.movies.aggregate([
  {
    $match: { countries: { $in: ["USA", 'China', 'Australia'] } }
  },
  {
    $project: {
      countries: {
        $size: { 
         $filter: {
           input: '$countries',
           cond: { '$in': [ '$$this', ["USA", 'China', 'Australia'] ] }
         }
       }
    }
  }
]);

That really should only be important to you where the array "within the document" contains entries that are not unique. i.e:

{ countries: [ "USA", "Japan", "USA" ] }

And you needed to count 2 for "USA", as opposed to 1 which would be the "set" result of $setIntersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!