首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带外键的MongoDB - OneToMany

带外键的MongoDB - OneToMany
EN

Stack Overflow用户
提问于 2015-11-23 09:02:02
回答 1查看 1.3K关注 0票数 4

我用的是mongodb v.2.6.11和猫鼬。

我有两个具有OneToMany关系的模型。在我的父母TypeA (简称TA)中,我没有提到孩子。在我的孩子TypeB (简称TB)中,我有一个对父母的id引用。

示例模式:

代码语言:javascript
复制
var TASchema = {
    name: {type: String, required: "TASchema.name is required", index: {unique: true, dropDups: true}}
}; 

var TBSchema  = {
    start: {type: Number, required: "TBSchema.language is required"},
    stop: {type: Number, required: "TBSchema.stop is required"},
    TA: {type: Schema.Types.ObjectId, ref: 'tbschema'},
}

我想做的是:选择所有在两个变量"ts_start“和"ts_stop”的时间段内具有"start“变量的TB (它们是时间戳)。比如:start : {$gte: ts_min, $lte : ts_max}

示例输出:

代码语言:javascript
复制
[
    {
       name: "Ta object 1",
       tbs: [{start : 1, stop2}, {start: 2, stop: 3}] 
    },
    {
       name: "Ta object 2",
       tbs: [{start : 1, stop2}, {start: 2, stop: 3}] 
    }
]

我希望保留查询返回TA数组的结构,其中每个TA都包含一个TB:s数组。但我不能使用populate,因为TA没有对子文档的任何引用(因为可能有太多的TA将其保存为子文档)。

那么,这是如何实现的呢?我是不是想错了,或者应该如何输出指定的查询,就像我的示例输出一样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-23 09:56:07

为了摆脱@vmkcom,尝试使用$match$group管道步骤来实现聚合框架,使用管道操作返回的结果填充TA字段,但修改TA模型的模式设计。这对于填充聚合的结果是必要的,因此在TA模式中向TB模式添加一个refs数组:

代码语言:javascript
复制
var TASchema = {
    name: { 
        type: String, 
        required: "TASchema.name is required", 
        index: {unique: true, dropDups: true}
    },
    tbs: [{ type: Schema.Types.ObjectId, ref: 'tbschema' }]
};

实现如下(未经测试):

代码语言:javascript
复制
var pipeline = [
    { 
        "$match": { 
            "start": { "$gte": ts_min, "$lte": ts_max }
        }
    },
    { 
        "$group": {
            "_id": "$TA",
            "tbs": {
                "$push": {  "start": "$start", "stop": "$stop" }
            }           
        }
    }
];
TBModel.aggregate(pipeline,
    function(err, results) {
        if (err) throw err; 
        var results = result.map(function(doc) { return new TAModel(doc) });        
        TBModel.populate(results, {"path": "TA"}, function(err, docs) {
            if (err) throw err;
            console.log(JSON.stringify(docs, undefined, 4));
        });
    }
);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33867047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档