mongodb - 如何从具有两个条件的子文档数组中选择元素?

标签 mongodb mongoose

考虑以下 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/

相关文章:

javascript - 使用多个键排序meteor mongodb

javascript - Mongoose 和 Typescript - 将模型链接到特定的 mongoose 连接

javascript - 使用纯 javascript/jquery 从 Mongodb 客户端读取 JSON

javascript - Mongoose :.save 不是函数

javascript - 从回调访问 'this' 范围变量

node.js - E11000 mongodb mongoose 中的重复键错误索引

javascript - 更新 mongoose 对象数组

Node.js res.send VS res.end VS 返回res.end

mongodb - Sails.js mongodb map 减少

java - 如何删除 Spring Mongo 查询中的条件