MongoDB查找匹配两个值

时间:2019-05-22 12:26:41

标签: mongodb mongodb-query aggregation-framework

我有两个集合,网球matches和两个球员和players

matches看起来像这样:

{ 
    "_id" : ObjectId("5ce51febc6dd820a820f20a5"), 
    "players" : [
        ObjectId("5ce51c1af3cd6009a171a5b3"), 
        ObjectId("5ce51c1af3cd6009a171a350")
    ], 
    "result" : "4:6 6:3 7:6(7) 7:6(8)"    
},
{ 
    "_id" : ObjectId("5ce51febc6dd820a820f20a6"), 
    "players" : [
        ObjectId("5ce51c1af3cd6009a171a005"), 
        ObjectId("5ce51c1af3cd6009a171a16c")
    ], 
    "result" : "6:2 4:6 6:3"    
},
[...]

players像这样:

{ 
    "_id" : ObjectId("5ce51c1af3cd6009a171a5b3"),               
    "name" : "Serena Williams",         
    "country" : "USA"         
},
{
    "_id" : ObjectId("5ce51c1af3cd6009a171a350"),               
    "name" : "Garbiñe Muguruza",         
    "country" : "Spain"         
},
[...]

我需要所有matches,其中players[0]等于一个名称 players[1]等于另一个名称。

我尝试了这个但没有成功:

db.matches.aggregate([
  {
    $unwind: "$players"
  },
  {
    $lookup: {
      from: "players",
      localField: "players",
      foreignField: "_id",
      as: "tmp_join"
    }
  },
  {
    $match: {
      "tmp_join.name": ["Serena Williams","Garbiñe Muguruza"]
    }
  }
])

1 个答案:

答案 0 :(得分:1)

您必须首先$unwind tmp_join数组,然后才能使用$in查找包含名称的文档。

db.matches.aggregate([
  { "$lookup": {
    "from": "players",
    "localField": "players",
    "foreignField": "_id",
    "as": "tmp_join"
  }},
  { "$unwind": "$tmp_join" },
  { "$match": {
    "tmp_join.name": {
      "$in": ["Serena Williams","Garbiñe Muguruza"]
    }
  }}
])

如果您使用的是mongodb 3.6 及更高版本

,请在聚合以下使用
db.matches.aggregate([
  { "$lookup": {
    "from": "players",
    "let": { "players": "$players" },
    "pipeline": [
      { "$match": {
        "$expr": { "$in": ["$_id", "$$players"] },
        "name": { "$in": ["Serena Williams", "Garbiñe Muguruza"] }
      }}
    ],
    "as": "tmp_join"
  }},
  { "$match": { "$expr": { "$gt": [{ "$size": "$tmp_join" }, 1] }}}
])