2015-06-15 41 views
0

我想在總管道使用$ geoWithin查詢,但我得到一個一個

MongoError: exception: bad query: BadValue bad geo query: { $geoWithin: { $box: [ [ "13.618240356445312", "51.01343066212905" ], [ "13.865432739257812", "51.09662294502995" ] ] } } 

我的查詢:

{ 
    $match: { 
     'gps.coordinates.matched': { 
      $geoWithin: { 
       $box: [ 
        [ swlng, swlat ], 
        [ nelng , nelat ] 
       ] 
      } 
     } 
    } 
}, 
{ $project : {shortGeohash: {$substr: ["$gps.geohash.original", 0, 11]}}}, 
{ $group: {_id: "$shortGeohash", count: {$sum:1}, originalDoc:{$push: "$$ROOT"}}} 

查詢只有$geoWithin以及$project...,$group自己運行良好,但組合發生錯誤。

+0

嗯。你真的用'[]'把你的管道封裝成適當的數組標識符嗎?更何況'$$ ROOT'沒有達到我認爲你期望的效果。它只是「當前」階段的「整個」文檔,而不是「$ project」修改之前的「原始」文檔。 –

+0

我以前沒有這樣做過,但是將它包裝成一個數組會導致相同的錯誤,在那裏沒有任何更改。的確,'$$ ROOT'沒有像我打算做的那樣工作,但它至少給了我'ObjectId',這對我來說工作得很好。 – florianschmidt1994

+0

你會更好地編輯你的問題,並提供人們可以測試和重現的例子。現在我只是說,「適合我」。但是,當你做錯了事情的時候,確實要把這個'$$ ROOT'的評論放在心上。 –

回答

0

我試過你的查詢,它似乎實際工作。我使用這樣的文檔對集合執行查詢。

[{ 
    "_id" : "5a2404674eb6d938c8f44856", 
    "code" : "M.12345", 
    "loc" : { 
     "type" : "Point", 
     "coordinates" : [ 
      41.9009789, 
      12.5010465 
     ] 
    } 
}, 
... 
] 

聚合管道是這樣的。

{ 
    $match: { 
     'loc': { 
      $geoWithin: { 
       $box: [ 
        [ 0, 0 ], 
        [ 5, 5 ] 
       ] 
      } 
     } 
    } 
}, 
{ $project : {subCode: {$substr: ["$code", 0, 4]}}}, 
{ $group: {_id: "$subCode", count: {$sum:1}, originalDoc:{$push: "$$ROOT"}}} 

其中一個結果是這樣的。

{ 
    "_id" : "M.10", 
    "count" : 12.0, 
    "originalDoc" : [ 
     { 
      "_id" : "5a2481c44eb6d92b6895633a", 
      "subCode" : "M.10" 
     }, 
     .... //11 more items 
    ] 
} 

使用mongod v3.4.9正確返回結果。