【发布时间】:2023-02-12 12:17:46
【问题描述】:
我有一个架构:
// mongoose schema
const MySchema = new Schema({ objWithDynamicKeys: { type: Map, of: String } });
const OtherSchema = new Schema({
limit: Number,
refToMySchema: { type: Schema.Types.ObjectId, ref: 'MyModel' },
name: String,
});
MySchema 模型的文档如下所示:
const doc = {
_id: new ObjectId("some-string"),
objWithDynamicKeys: {
"62f74bcfd4aa7ff5c45c7fe3": 2,
"62f74bcfd4aa7ff5c45c7fe4": 5,
"62f74bcfd4aa7ff5c45c7fe5": 1,
}
OtherSchema 模型的文档如下所示:
const otherDoc1 = {
_id: new ObjectId("62f74bcfd4aa7ff5c45c7fe3"),
limit: 5,
name: "First",
};
const otherDoc2 = {
_id: new ObjectId("62f74bcfd4aa7ff5c45c7fe4"),
limit: 5,
name: "Second",
};
const otherDoc3 = {
_id: new ObjectId("62f74bcfd4aa7ff5c45c7fe5"),
limit: 3,
name: "Third",
};
我正在构建一个聚合,它应该找到所有 OtherSchema 文档,其 _id 是 MySchema 文档的 objWithDynamicKeys 中的键,其中 objWithDynamicKeys 的值小于相应文档的 limit。
所以在运行聚合后我想要有以下输出:
[
{
_id: new ObjectId("62f74bcfd4aa7ff5c45c7fe3"), // doc1
limit: 5,
name: "First",
},
{
_id: new ObjectId("62f74bcfd4aa7ff5c45c7fe5"), // doc3
limit: 5,
name: "Third",
},
];
如果objWithDynamicKeys 是一个数组,那就没那么难了。
{
$lookup: {
from: 'othercollection',
localField: 'objWithDynamicKeys',
foreignField: '_id',
as: 'out',
pipeline: [
{
$match: {
$expr: {
$lt: ['$field_from_somewhere', '$limit'],
},
},
},
],
},
},
我怎样才能做到这一点?甚至有可能做吗?
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework mongoose-schema