2017-08-04 93 views
0

第一场我有一个看起来像这样的文档集合:的MongoDB:查询在子文档

{ 
    "_id": "12345", 
    "Company Name" : "Foo Inc.", 
    "Address": "123 bar street", 
    "Financials" : { 
      "Last Year" : "2016", 
      "Balance Sheet" : { 
       "2016" : { 
        "Total Assets" : 123.0, 
        "Current Assets" : 456.0, 
        "Current Liabilities" : 789.0, 
        "Shareholders Equity" : -123.0 
       }, 
       "2015": { 
        "Total Assets": 123.0, 
        "Current Assets": 456.0, 
        "Current Liabilities": 789.0, 
        "Shareholders Equity": -123.0 
       } 
      }, 
} 

我可以以某种方式查询最近一年的总资产不知道是哪一年?类似于Financials.Balance表。{latest_year}。总资产。 理想我想这样做对整个集合即

db.find({'Financials.Balance Sheet.{last_year}.Total Assets' : {$gt: 1000}}) 

我有最新的一年称为去年单独的领域是否有帮助

+0

更多的是这里选择的文档结构对于其预期目的而言非常糟糕的情况。将数组放在数组中而不是使用指定键会让你变得更好。命名键是一个“anit-pattern”,不能通过计算被MongoDB“动态”查询。保持一致的路径是最佳选择,然后您甚至可以“索引”数据以便更快地进行选择。你不能用钥匙做到这一点。 –

回答

0

您应该更新您的结构如下。

{ 
    "_id": "12345", 
    "Company Name": "Foo Inc.", 
    "Address": "123 bar street", 
    "Financials": { 
    "Last Year": 2016, 
    "Balance Sheet": [ 
     { 
     "year": 2016, 
     "Total Assets": 123, 
     "Current Assets": 456, 
     "Current Liabilities": 789, 
     "Shareholders Equity": -123 
     }, 
     { 
     "year": 2015, 
     "Total Assets": 123, 
     "Current Assets": 456, 
     "Current Liabilities": 789, 
     "Shareholders Equity": -123 
     } 
    ] 
    } 
} 

现在查询是非常简单

{'Financials.Balance Sheet" : {$elemMatch: {"year" : 2016, "Total Assets":{$gt:1000}}}} 

但因为某些原因,如果你不能改变你的结构,可以在当前3.4版本使用下面聚集查询。

{ 
    "$redact": { 
    "$cond": [ 
     { 
     "$let": { 
      "vars": { 
      "first": { 
       "$arrayElemAt": [ 
       { 
        "$objectToArray": "$Financials.Balance Sheet" 
       }, 
       0 
       ] 
      } 
      }, 
      "in": { 
      "$gt": [ 
       "$$first.v.Total Assets", 
       1000 
      ] 
      } 
     } 
     }, 
     "$$KEEP", 
     "$$PRUNE" 
    ] 
    } 
}