MongoDB find & group similar items

浪子不回头ぞ 提交于 2020-03-25 05:51:49

问题


I have a table for teams that looks as shown below:

I am just displaying the fields that I am interested in. I was wondering how I can get the teams with goals for and against that have the same value of goals for and goals against. For example in the table above it should be:

Italy    4    5
Mexico   4    5
England  3    5
Chile    3    5

The answers should be distinct as well.

This is what I have so far:

var team1 = db.Teams.find();
var team2 =db.Teams.find();
team1.forEach(function(item){team2.forEach(function(item2){if (item.goalsFor == item2.goalsFor && item.goalsAgainst == item2.goalsAgainst) {print(item2.team, item2.goalsFor, item2.goalsAgainst);}})})

Thanks.


回答1:


You can try below query :

db.collection.aggregate([
  /** Group on 'goalsFor' & 'goalsAgainst' for similars & push teams to 'teams' array,
  *  Will be one or more (if there are any similar teams with same 'goalsFor' & 'goalsAgainst' then that doc will have 2 or more elements/teams in teams array) */
  {
    $group: {
      _id: { goalsFor: "$goalsFor", goalsAgainst: "$goalsAgainst" },
      teams: { $push: "$team" }
    }
  },
  /** Filter docs where there are multiple teams in 'teams' array */
  { $match: { $expr: { $gte: [{ $size: "$teams" }, 2] } } }
]);

Test : MongoDB-Playground

Update to Answer :

For MongoDB version 2.6.10, try below query :

db.collection.aggregate([
  {
    $group: {
      _id: {
        goalsFor: "$goalsFor",
        goalsAgainst: "$goalsAgainst"
      },
      teams: {
        $push: "$team"
      }
    }
  },
  {
    $project: {
      teams: 1,
      _id: 0,
      goalsFor: "$_id.goalsFor",
      goalsAgainst: "$_id.goalsAgainst",
      teamsSize: {
        $size: "$teams"
      }
    }
  },
  {
    $match: {
      teamsSize: {
        $gte: 2
      }
    }
  },
  {
    $project: {
      teamsSize: 0
    }
  }
])

Test : MongoDB-Playground



来源:https://stackoverflow.com/questions/60793489/mongodb-find-group-similar-items

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