簡體   English   中英

在$ lookup之后Mongodb $接近

[英]Mongodb $near after $lookup

如果位置坐標在另一個集合中,如何使用$ near查詢服務?

$ lookup,$ near

我有2個集合,一個用於用戶,另一個用於服務。
用戶集合是:

{ "_id" : ObjectId("570557d4094a4514fc1291d6"), "fullname" : "John Doe",
"position" : {
    "street" : "Piazza Santa Maria",
    "city" : "Busto",
    "country" : "Italy",
    "zip_code" : "21052",
    "address" : "Piazza Santa Maria, 21052 Busto, Province of Varese, Italy",
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            8.8502715, 
            45.6114064
        ]
    },
    "country_code" : "IT",
    "state" : "Lombardy",
    "province" : "Province of Varese"
 }
}

}

服務集合是:

{ "_id" : ObjectId("960557d4094a4514fc1291a7"), 
author_id : ObjectId("570557d4094a4514fc1291d6"), title:"Software developer"}
{ "_id" : ObjectId("960557d4094a4514fc1291a7"), 
author_id : ObjectId("570557d4094a4514fc1291d6"), title:"App developer"}

我想根據作者位置查找服務集合中的所有文檔。

首先,您需要滿足MongoDB基於位置的查詢的幾個要求。

  1. users集合上創建2dsphere索引
  2. $geoNear階段應該是聚合管道的第一階段。

例:

db.users.aggregate([
  {
    $geoNear: {
      near: {type: "Point", coordinates: [ 8.840 , 45.6114060 ]},
      distanceField: "dist.calculated",
      maxDistance:1000,
      spherical: true
  }},
  {
    $lookup: {
      from:"services", localField:"_id", foreignField:"author_id", as: "services"
  }}
])

在這里,我們試圖找到1000米范圍內的文件。 在這種情況下,位置文件[8.8502715, 45.6114064]

輸出

{ 
    "_id" : ObjectId("570557d4094a4514fc1291d6"), 
    "fullname" : "John Doe", 
    "position" : {
        "street" : "Piazza Santa Maria", 
        "city" : "Busto", 
        "country" : "Italy", 
        "zip_code" : "21052", 
        "address" : "Piazza Santa Maria, 21052 Busto, Province of Varese, Italy", 
        "location" : {
            "type" : "Point", 
            "coordinates" : [
                8.8502715, 
                45.6114064
            ]
        }, 
        "country_code" : "IT", 
        "state" : "Lombardy", 
        "province" : "Province of Varese"
    }, 
    "dist" : {
        "calculated" : 799.8404739526889
    }, 
    "services" : [
        {
            "_id" : ObjectId("960557d4094a4514fc1291a7"), 
            "author_id" : ObjectId("570557d4094a4514fc1291d6"), 
            "title" : "Software developer"
        }, 
        {
            "_id" : ObjectId("580d499eb22270301913d677"), 
            "author_id" : ObjectId("570557d4094a4514fc1291d6"), 
            "title" : "Software developer"
        }, 
        {
            "_id" : ObjectId("580d499eb22270301913d678"), 
            "author_id" : ObjectId("570557d4094a4514fc1291d6"), 
            "title" : "App developer"
        }
    ]
}

如果我們在谷歌地圖上繪制兩個文件進行驗證,我們就會得到

谷歌地圖圖片

正如您在圖像上看到的那樣,我們的文檔位置大約相距800米,因此在查詢中指定的1000米范圍內。 請參閱Goole地圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM