【发布时间】:2018-10-02 23:09:31
【问题描述】:
假设我在数据库中有以下文档结构:
{ name: String,
subDocs: [{
index: Number,
value: Number
}]
}
所以一个典型的文档看起来像:
{ name: 'Document 1',
subDocs: [
{ index: 0, value: 30 },
{ index: 1, value: 40 },
{ index: 2, value: 10 },
{ index: 3, value: 20 },
{ index: 4, value: 700 },
{ index: 5, value: 40 }
]
}
现在,我想查找包含值 A = 10 和 B = 40 的子文档的所有文档,但数组中项目的出现必须满足以下要求 A.index
{ name: 'Document 2',
subDocs: [
{ index: 0, value: 40 },
{ index: 1, value: 70 },
{ index: 2, value: 10 },
{ index: 3, value: 20 },
{ index: 4, value: 700 }
]
}
我们可以在不牺牲这种查询性能的情况下使用 Mongoose 实现它吗?
【问题讨论】:
-
拿到文档后为什么不对它们进行排序?
-
嗨@GeorgeBailey。你能详细说明一下这个想法吗?我认为在这种情况下排序没有帮助。我还希望所有工作都由 MongoDB 引擎完成,因此我不需要在我的后端代码中额外过滤它。
-
您提到的对象包含 10,20 以外的值?你的问题有点不清楚对不起:p
-
对不起,如果问题不清楚。字段“值”是一个整数,因此它可以保存您可以成像的任何有效整数:)
-
其中包含值为 A = 10 和 B = 40 的子文档,那么,这怎么能是预期的输出呢?
{ name: 'Some name', subDocs: [ { index: 0, value: 30 }, { index: 1, value: 40 }, { index: 2, value: 10 }, { index: 3, value: 20 }, { index: 4, value: 700 }, { index: 5, value: 40 } ] }
标签: mongodb mongoose mongodb-query