【问题标题】:Return the embedded documents that match the query返回与查询匹配的嵌入文档
【发布时间】:2018-02-04 19:10:45
【问题描述】:

我有一个这样的模型

{
    _id: '5a7745529c69b22fe5d6f321',
    array: [{
        name: 'a',
        something: 'something1'
    },{
        name: 'b',
        something: 'something2'
    },{
        name: 'a',
        something: 'something2'
    }]
}

我需要获取所有名称为a的嵌入文档

The output must be
    [{
        name: 'a',
        something: 'something1'
    },{
        name: 'a',
        something: 'something2'
    }]

当我使用 unwind 时,它会为每个文档提供数组键。我想要的输出与上面完全相同。我怎样才能做到这一点?

【问题讨论】:

  • @JohnnyHK 。我认为您确实了解我期望的输出。我不希望我的结果被包装在一个对象中,然后将数组附加到一个键上。我希望直接使用数组。

标签: mongodb mongoose aggregation-framework


【解决方案1】:

试试;

db.collection_name.aggregate([
 { $unwind : “$array” },
 { $match : { name : “a” } },
 { $project : { _id : 0, array : 1 } }
 ])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2020-02-19
    • 2015-03-26
    相关资源
    最近更新 更多