MongoDB $ elemMatch显示问题

时间:2013-07-04 14:24:04

标签: mongodb bson

列出了测试集合中的以下示例文档

我的要求是仅提取“两个字段” “host.name”和“host.config.storageDevice.scsiLun.lunType”匹配条件“host.config.storageDevice.scsiLun.lunType”:“cdrom1”和“host.name”:“on-xxx”

就像我上面提到的,我只希望属性“lunType”显示在数组中而不是“a”或“b”

我试图同时使用$ elemMatch和$ projection,它似乎总是返回数组“lunType”的所有属性......我在这里遗漏了什么

参考文件时尝试过 http://docs.mongodb.org/manual/reference/projection/elemMatch/

查询

db.test.find({“host.config.storageDevice.scsiLun”:{$ elemMatch:{“lunType”:“cdrom1”}}},{“host.name”:1,“host.config。 storageDevice.scsiLun。$“:1})

db.test.find({“host.config.storageDevice.scsiLun.lunType”:“cdrom1”},{“host.name”:1,“host.config.storageDevice.scsiLun。$”:1} )

收藏中的文件

    {
    "_id" : ObjectId("51d57f3ad4ebc6c87962d4c0"),
    "host" : {
    "name" : "on-xxx",
    "config" : {
        "storageDevice" : {
            "scsiLun" : [ 
                {
                    "a" : "1",
                    "lunType" : "cdrom1"
                }, 
                {
                    "a" : "2",
                    "lunType" : "disk2"
                }, 
                {
                    "a" : "3",
                    "lunType" : "disk3"
                }
            ]
        }
        }
    }
    }
    , 
    {
    "_id" : ObjectId("51d57f59d4ebc6c87962d4c1"),
    "host" : {
    "name" : "on-yyy",
    "config" : {
        "storageDevice" : {
            "scsiLun" : [ 
                {
                    "a" : "4",
                    "lunType" : "cdrom4"
                }, 
                {
                    "a" : "5",
                    "lunType" : "disk5"
                }, 
                {
                    "a" : "6",
                    "lunType" : "disk6"
                }
            ]
        }
       }
    }
    }
    , 
    {
    "_id" : ObjectId("51d57f74d4ebc6c87962d4c2"),
    "host" : {
    "name" : "on-zzz",
    "config" : {
        "storageDevice" : {
            "scsiLun" : [ 
                {
                    "a" : "7",
                    "lunType" : "cdrom11"
                }, 
                {
                    "a" : "8",
                    "lunType" : "disk22"
                }, 
                {
                    "a" : "9",
                    "lunType" : "disk32"
                }
            ]
        }
    }
    }
    }

1 个答案:

答案 0 :(得分:2)

所有$ elemMatch都是返回匹配条件的数组的第一个元素,但它将为您提供整个元素,即“a”和“lunType”属性。

aggregation使用$unwind分解数组,然后$match过滤而$project仅显示“lunType”字段,可以获得所需的结果。

我没有测试查询,但它应该如下所示:

    db.test.aggregate(
        { $unwind : "$host.config.storageDevice.scsiLun" },
        { $match : { host.name : "on-xxx" , 
             host.config.storageDevice.scsiLun.lunType : "cdrom1" } },
        { $project : {
            _id : 0 ,
            host.config.storageDevice.scsiLun.lunType : 1 }
    );