Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 在Mongo中,$near和$nearSphere之间有什么区别?_Mongodb - Fatal编程技术网

Mongodb 在Mongo中,$near和$nearSphere之间有什么区别?

Mongodb 在Mongo中,$near和$nearSphere之间有什么区别?,mongodb,Mongodb,我看了这些文件,不太清楚两者之间的区别 我发现的唯一区别是,在nearSphere中,它明确表示Mongo使用球形几何体计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?关键字是sphere来区分和 如您所知,$nearSphere用于使用球形几何体计算距离。这与地球有关()。何处为基础,何处为基础 足够的理论,让我们用一些例子。假设我们有两份文件,如下所示: db.map.insert({ "_id": "Westfield London", "location":

我看了这些文件,不太清楚两者之间的区别


我发现的唯一区别是,在nearSphere中,它明确表示Mongo使用球形几何体计算$nearSphere的距离。但是使用$near也可以实现这一点,不是吗?

关键字是
sphere
来区分和

如您所知,
$nearSphere
用于使用球形几何体计算距离。这与地球有关()。何处为基础,何处为基础

足够的理论,让我们用一些例子。假设我们有两份文件,如下所示:

db.map.insert({ "_id": "Westfield London", "location": [ -0.22157, 51.507176 ] });
db.map.insert({ "_id": "Green Lanes Shopping Centre", "location": [ -0.098092, 51.576198 ] });
两个操作员的手册都规定我们可以使用:

  • 2dsphere
    定义为点的位置数据索引
  • 2d
    位置数据索引定义为
索引:2dsphere,查询:GeoJSON

db.map.createIndex({"location": "2dsphere"});

db.map.find({"location":{"$nearSphere":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ] }}}});

db.map.find({"location":{"$near":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ]}}}});
在这种情况下,两个查询将返回相同的结果,因为索引存储在
2dsphere

结果:

[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Green Lanes Shopping Centre"},
    {"_id" : "Westfield London"}
]
索引:2d,查询:传统坐标

db.map.createIndex({"location": "2d"});

db.map.find({"location":{"$nearSphere":[ -0.127748, 51.507333 ]}});

db.map.find({"location":{"$near":[ -0.127748, 51.507333 ]}});
这就是区别发生的地方,
$nearSphere
的结果是在不考虑索引的情况下球形计算的,而
$near
是在平面投影中计算的

结果:

[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $nearSphere */
    {"_id" : "Westfield London"},
    {"_id" : "Green Lanes Shopping Centre"}
]
[ /* $near */
    {"_id" : "Green Lanes Shopping Centre"},
    {"_id" : "Westfield London"}
]
请参见上面示例的一部分。这是使用MongoDB v3.4.4进行测试的


另见

我有完全相同的审问。你找到什么了吗?