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

示例模式:
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}。
示例输出:
[
{
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将其保存为子文档)。
那么,这是如何实现的呢?我是不是想错了,或者应该如何输出指定的查询,就像我的示例输出一样?
发布于 2015-11-23 09:56:07
为了摆脱@vmkcom,尝试使用$match和$group管道步骤来实现聚合框架,使用管道操作返回的结果填充TA字段,但修改TA模型的模式设计。这对于填充聚合的结果是必要的,因此在TA模式中向TB模式添加一个refs数组:
var TASchema = {
name: {
type: String,
required: "TASchema.name is required",
index: {unique: true, dropDups: true}
},
tbs: [{ type: Schema.Types.ObjectId, ref: 'tbschema' }]
};实现如下(未经测试):
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));
});
}
);https://stackoverflow.com/questions/33867047
复制相似问题