如何通过MongoDB中的嵌套字段连接到集合

时间:2019-01-26 21:50:32

标签: mongodb spring-data

我在MongoDB中遇到一些查询问题。假设我有一个排名表

{
   "competitions: {id: "1", name:"someLeague"},
   "standings": [
      {
         "type": "TOTAL",
         "table": [
            {
               "position": "1",
               "team": {
                  "id": "123",
                  "name": "XYZ"
               },  
               won: "1",
               draw: "2",
               lost: "3",
               points: "4",
            },
            {
               "position": "2",
               "team": {
                  "id": "321",
                  "name": "ABC"
               }
                      ...

还有看起来像

的装置集合
{
   matchDay: "YYYY-MM-DD",
   homeTeam: {id:  "123", name:"ABC"}, 
   awayTeam: {id:  "321", name:"XYZ"},
}

是否可以通过这种方式将这两个集合连接起来,以便灯具集合中的“ homeTeam”字段将包含所有类型的积分信息,包括积分,获胜游戏等?和场外球队相同,条件是球队的信息将来自积分榜类型不在的阵型。

1 个答案:

答案 0 :(得分:0)

在MongoDB中无法引用集合B中集合A的文档,因此对集合B的find查询将自动提供所引用文档的属性。但是,从MongoDB 3.2开始,可以在查询过程中使用$lookup命令作为aggregation(请参见https://stackoverflow.com/a/33511166/3976662)的一部分来联接(类似于标准SQL)多个查询。就您而言,您可以考虑将$lookup$unwind结合使用-类似to the example in the MongoDB docs。 Spring Data Mongo支持$lookup since 1.10