MongoDB不是那么简单的找到

时间:2015-11-06 19:57:13

标签: javascript mongodb

我想建立什么:

我在mongo中有这样的东西:

{
  team1: 'Love',
  team2: 'Popa',
  score: 3
}
{
  team1: 'Love'
  team2: 'Ola'
  score: 1
}
{
  team1: 'Popa'
  team2: 'Ola'
  score: 5
}
{
  team1: 'Popa'
  team2: 'Kola'
  score: 56
}

form 2 inputs喜欢

<input type="text" id="team1" placeholder="Team 1">
<input type="text" id="team2" placeholder="Team 2">

Soo例如我放入了第一个输入组Love和第二个组Popa

我希望与两支球队一起在mongo中展示得分游戏,对于我的例子这个将是团队Ola

如果您了解我要构建的内容,请帮助我创建Posts.find(.... 谢谢!

更新:我的想法是如何做到的 1.

    Posts.find({team1: 'Love'}).map(function(item){ return item.team2; });
    Posts.find({team2: 'Love'}).map(function(item){ return item.team1; });
// disaply all team that plays with first team that I put in first input
    Posts.find({team1: 'Popa'}).map(function(item){ return item.team2; });
    Posts.find({team2: 'Popa'}).map(function(item){ return item.team1; });
// disaply all team that plays with first team that I put in first input
// out put will be look like [Popa,Ola] - first team , [Popa,Ola,Kola] - second team
  1. 使用包含在两个arrray中的单词创建数组。 [Popa,Ola]
  2. 删除'Popa',因为Popa无法使用Popa lol,就像Team1与Team1 [Ola]
  3. 一样
  4. 我需要与两个小组一起显示分数,例如
  5. Ola vs Love (1),Ola vs Popa (5)id(在mongo中)此游戏

    UPDATE2 07.11.2015 找不到解决方案,请帮忙!

2 个答案:

答案 0 :(得分:0)

我假设您的收藏名称为Posts

db.Posts.find({team1:"Love"}).forEach(function(doc){
    printjson(db.Posts.findOne({team1:"Popa", team2:doc["team2"]}));
})

答案 1 :(得分:0)

db.Posts.ensureIndex({team1:1,team2:1});

var teams = [];

db.Posts.find(
    {$or:[{team1:'Love'},{team2:'Love'}]},
    {team1:1,team2:1,_id:0}
).forEach(function(doc){
    if(doc.team1 === 'Love'){
        teams[teams.length] = doc.team2;
    }else{
        teams[teams.length] = doc.team1;
    }
});

var actualTeams = [];

db.Posts.find(
    {$or:[
        {team1:'Popa', team2:{$in:teams}},
        {team2:'Popa', team1:{$in:teams}}
    ]},
    {_id:0,team1:1,team2:1}
).forEach(function(doc){
    if(doc.team1 === 'Popa'){
        actualTeams[actualTeams.length] = doc.team2;
    }else{
        actualTeams[actualTeams.length] = doc.team1;
    }
});

类似的东西和actualTeams将包含交叉引用,并且您只对DB执行了两次查询。