MongoDB查找和将类似项目分组 [英] MongoDB find & group similar items

查看:91
本文介绍了MongoDB查找和将类似项目分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个团队表,如下所示:

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

答案也应该是不同的.

这是我到目前为止所拥有的:

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);}})})

谢谢.

推荐答案

您可以在下面的查询中进行尝试:

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] } } }
]);

测试: MongoDB-Playground

更新为答案:

对于MongoDB版本2.6.10,请尝试以下查询:

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
    }
  }
])

测试: MongoDB-Playground

这篇关于MongoDB查找和将类似项目分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆