0

我有一个具有以下架构的复杂位置数据库:

table States
id : INT PK AutoIncrement
name : VarChar 50 UNIQUE

table Counties 
id: INT PK AutoIncrement
stateID : INT ForeignKey ->States(id)
name : VARCHAR(50)

table Towns : 
id: INT PK AutoIncrement
stateID : INT ForeignKey ->States(id)
countyID : INT ForeignKey ->Counties(id)
name : VARCHAR(50)

table listings
id : INT PK autoincrement
name: varchar(50)
stateID: INT
countyID:  INT
townID:  INT

当我想以这样的树形显示有关地理重新分区的一些统计数据时:

  • state1(105 个结果)
    • 县 1(50 个结果)
    • 县 2(55 个结果)
      • 城镇 1 ( 20 个结果)_
      • 城镇 2 ( 35 个结果)
  • state2(200 个结果)等...

在 mySQL 中,我会做这种查询:

**第一级:**

 select count(*) as nb, S.namem, S.id as stateID from listings L INNER JOIN States S ON S.id=L.stateID GROUP BY S.id;

**二维级别:**

 foreach(results as $result){
      $sql = "select count(*) as nb, from listings L INNER JOIN Counties C ON C.id=L.countyID WHERE L.stateID=".$result['stateID'];
 });

等等......在 MySQL 的独特长查询中也有一种方法可以做到这一点。

这是一个简单的查询,它在 Mysql 的 SSD 磁盘上非常快。

我开始学习 mongoDB,我想知道应该使用哪种模式来存储我的位置数据以优化 $count() 和 $group() 操作。

哪个 mongo 查询可以完成这项工作?

4

1 回答 1

1

使用类似listings表格的结构存储文档:

{
    "name" : "listing0",
    "state" : "Maryland",
    "county" : "Washington",
    "town" : "Faketown"
}

然后只需使用聚合管道找到每个(州、国家、城镇)三倍的房源数量

> db.listings.aggregate([
    // hopefully an initial match stage to select a subset of search results or something
    { "$group" : { "_id" : { "state" : "$state", "county" : "$county", "town" : "$town" }, "count" : { "$sum" : 1 } } }
])

从这里您可以通过迭代结果光标来计算树的更高级别的数字,或者您可以运行类似的管道来计算树的更高级别的数字。例如,对于特定州的县编号

> db.listings.aggregate([
    // hopefully an initial match stage to select a subset of search results or something
    { "$match" : { "state" : "Oregon" } },
    { "$group" : { "_id" : { "state" : "$state", "county" : "$county" }, "count" : { "$sum" : 1 } } }
])
于 2014-09-25T16:10:39.103 回答