【问题标题】:Mongo: how to retrieve ONLY subdocs that match certain propertiesMongo:如何仅检索与某些属性匹配的子文档
【发布时间】:2016-04-15 01:58:20
【问题描述】:

例如,有一个名为 test 的集合,其中包含以下文档:

{
    "_id" : ObjectId("5692ac4562c824cc5167379f"),
    "list" : [ 
        {
            "name" : "elem1",
            "type" : 1
        }, 
        {
            "name" : "elem2",
            "type" : 2
        }, 
        {
            "name" : "elem3",
            "type" : 1
        }, 
        {
            "name" : "elem4",
            "type" : 3
        }, 
        {
            "name" : "elem4",
            "type" : 2
        }
    ]
}

假设我想检索list 中匹配的子文档的列表:

  • type = 2

我尝试了以下查询

db.getCollection('test').find({
    '_id': ObjectId("5692ac4562c824cc5167379f"),
    'list.type': 1
})

但我得到的结果包含list 内的每个 子文档,我猜这是因为list 内至少有一个类型为等于 1 的文档.

取而代之的是,我有兴趣获得的结果将是list 中与'list.type': 1 匹配的每个子文档

{
    "_id" : ObjectId("5692ac4562c824cc5167379f"),
    "list" : [ 
        {
            "name" : "elem1",
            "type" : 1
        }, 
        {
            "name" : "elem3",
            "type" : 1
        }
    ]
}

...所以$$elemMatch 并不是我真正想要的,因为它们只返回第一个匹配元素。

有人知道如何实现我的目标吗?

【问题讨论】:

标签: mongodb mongoose mongodb-query


【解决方案1】:
db.myCol.aggregate([ 
                    { $unwind: "$list" }, 
                    { $match: { "list.type":1 } }, 
                    { $group: { "_id":"$_id", list: {$push:"$list"}} }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2011-09-26
    相关资源
    最近更新 更多