gpt4 book ai didi

javascript - 设计集合,如何去规范化

转载 作者:行者123 更新时间:2023-12-03 10:45:29 26 4
gpt4 key购买 nike

我在许多地点都以不同的价格提供服务。在过渡 SQL 中,当我想在某些区域中查找显示最高和最低价格的服务(区域将选择多个位置)时,我会让包含 service_id 和 location_id 的 Price_location 表进行联接和分组。

由于服务和位置非常多,我正在考虑以下内容:

service_location_price = [
{
serviceName:'s1';
,price:10
,location:'location1'
},{//to keep it simple only serviceName is here but
// there will be multiple providers for the same
// serviceName at same location but different price
serviceName:'s1';
,price:12
,location:'location1'
},{
serviceName:'s1';
,price:15
,location:'location2'
}
];

基本上是平面文件数据,打破了第二范式(具有重复的行)。

现在聚合和/或 map 缩减应该可以很好地让某个区域的服务显示最低和最高价格。或显示可提供某些服务的位置。

服务和位置都有自己的集合,service_location_price 集合会复制此查询的服务和位置的一些值。

有些人担心重复数据,并希望以不同的方式实现( Mongoose 用匹配填充?)。

不确定我的选择是什么,因此希望有更多经验的人提供一些意见。有没有更好的方法让搜索达到

服务和位置不会更新太多,但它们之间的关系可能会改变、添加或删除。但区域内的服务搜索会经常执行。

最佳答案

填充是一个大型的 $in 查询,用于解析引用,然后将数组中的引用替换为相应的文档。如果引用字段被索引,这还不错,但它是一个额外的查询,并且是糟糕的模式设计的拐杖,因为当您不使用关系数据库时,它可以更容易地模拟关系数据库,并且应该以不同的方式处理问题。我认为它应该从 Mongoose 中删除,但遗憾的是有点晚了:(

我不确定您如何对区域进行建模 - 您说一个区域可以是多个位置,因此我将把一个区域建模为 location 值的数组。

给定区域的服务总数:

db.service_location_price.distinct("serviceName", { "location" : { "$in" : region_array } })

这将为您提供一个服务名称数组,因此 .length 将给出服务的数量。

某个地区服务的最低/最高价格:

db.service_location_price.find({ "location" : { "$in" : region_array }, "serviceName" : "service1" }).sort({ "price" : 1 }).limit(1)
db.service_location_price.find({ "location" : { "$in" : region_array }, "serviceName" : "service1" }).sort({ "price" : -1 }).limit(1)

示例文档中没有有关服务 vendor 的信息,因此我不知道如何查找某个地区内服务 vendor 的数量。也许您想在文档中包含 supplier 字段?

关于javascript - 设计集合,如何去规范化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28581034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com