MongoDB上的历史数据结构

时间:2017-11-21 11:06:25

标签: mongodb

基于某个时间间隔,我需要根据以下模型实现预聚合的统计数据:

我有一个UPDATE wp_options SET option_value = replace(option_value, 'http://live_ste_path.com', 'http://localhost/local_site_path') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET post_content = replace(post_content, 'http://live_ste_path.com', 'http://localhost/local_site_path'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://live_ste_path.com','http://localhost/local_site_path')` 实体和Product实体,它扮演Products容器的角色。我可以拥有0..N产品和0..N产品组,产品和产品组之间具有ProductGroup关系。

根据自己的业务逻辑,我可以计算每个ProductGroup中每个产品的顺序。

我会在一段时间内不断地进行计算......让我们说通过Cron工作。

我还希望存储每个计算(版本)的历史记录,以便能够分析MANY_2_MANY位置变化。

我用这种结构创建了一个简单的图片:

enter image description here

现在我使用MongoDB数据库并且真的有兴趣在不引入新技术的情况下在MongoDB上实现这种结构。

我的功能要求 - 我需要能够快速获取特定Product中某些Product的位置(和位置偏移)。我们说ProductGroup的{​​{1}}位置和偏移量。输出应为:

P2

此外,我想要显示图形并显示具有特定ProductGroup的特定产品的头寸的历史变化。例如,对于ProductGroup1中的Product ProductGroup1,输出应为:

position: 1
offset  : +2

是否可以使用MongoDB实现?如果可以,您能否描述一下MongoDB集合结构以支持它?

1 个答案:

答案 0 :(得分:1)

由于唯一的限制是“按我在问题中描述的那样快速查询数据”,最简单的方法是使用一系列产品来创建快照集合:

db.snapshots.insert({
    group: "group 1", 
    products:[
        {id:"P2", position:0, offset:0},
        {id:"P4", position:1, offset:0},
        {id:"P5", position:2, offset:0},
        {id:"P6", position:3, offset:0}
    ], ver:0
});

db.snapshots.insert({
    group: "group 1", 
    products:[
        {id:"P3", position:0, offset:0},
        {id:"P5", position:1, offset:1},
        {id:"P1", position:2, offset:0},
        {id:"P2", position:3, offset:-3},
        {id:"P4", position:4, offset:0}
    ], ver:1
});

索引是

db.snapshots.createIndex(
    { group: 1, ver: -1,  "products.id": 1 }, 
    { unique: true, partialFilterExpression: { "products.id": { $exists: true } } } 
);

用于获取组中产品当前位置的查询(示例中“组1”中的“P4”):

db.snapshots.find(
    { group: "group 1" }, 
    { _id: 0, products: { $elemMatch: { id: "P4" } } }
).sort( { ver:-1 } ).limit(1)

获取历史数据的查询几乎相同:

db.snapshots.find(
    { group: "group 1" }, 
    { _id: 0, products: { $elemMatch: {id: "P4" } }, ver: 1 }
).sort({ver:-1})