考虑以下 Mongoose 架构:
new mongoose.Schema({
attributes: [{
key: { type: String, required: true },
references: [{
value: { type: String, required: true },
reference: { type: mongoose.Schema.Types.ObjectId, required: true }
}]
}
});
遵循此架构的文档将如下所示:
{
attributes: [
{
key: 'age', references: [{ value: '35', reference: 298387adef... }]
},
{
key: 'name', references: [{
value: 'Joe', reference: 13564afde...,
value: 'Joey', reference: 545675cdab...,
}
...
]
}
我想根据以下条件选择属性:
- 例如,键是 name
- 具有键 name
的属性至少有一个值为 Joe
的引用。
理想情况下,我想对其中许多条件进行 AND 链接。例如,{'name': 'Joe'}
和 {'age': '35'}
。
我似乎找不到一种方法来做到这一点。我尝试了以下 Mongoose 查询,但没有任何好的结果(它给出了误报或漏报):
// First query
query.where('attributes.key', attribute.key);
query.where('attributes.references.value', attribute.value);
// Second
query.and([{ 'attributes.key': attribute.key }, { 'attributes.$.references.value': attribute.value }]);
// Third
query.where('attributes', { 'key': attribute.key, 'references.value': { $in: [attribute.value] }});
那么我该怎么做呢?
最佳答案
您可以使用elemMatch
查找包含与多个术语匹配的 attributes
元素的文档:
query.elemMatch(attributes, { key: 'name', 'references.value': 'Joe' })
不过,您无法将多个 elemMatch
调用链接在一起,因此,如果您想要对多个调用进行 AND 操作,则需要使用 $and
显式构建一个查询对象> 和 $elemMatch
而不是链接 Query
方法调用。
关于mongodb - 如何从具有两个条件的子文档数组中选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16790101/