检索MongoDB集合中对象数组中的查询元素

时间:2017-06-20 15:02:18

标签: mongodb

我正在使用像这样的MongoDB文档

{
    "_id" : "toy_in_en_L02B",
    "modelCode" : "L02B",
    "path" : "/toy/in/en",
    "dataPath" : "/toy/in/en/L02B",
    "basicModelInformation" : {
        "name" : "News",
        "startingPrice" : "1234.0"
    },
    "grades" : {
        "grades" : [ 
            {
                "key" : "LVL001",
                "dataPath" : "/toy/in/en/L02B",
                "name" : "XE P",
                "price" : "1234.0"
            }, 
            {
                "key" : "LVL002",
                "dataPath" : "/toy/in/en/L02B",
                "name" : "XE P",
                "price" : "1234.0"
            },
            {
                "key" : "LVL003",
                "dataPath" : "/toy/in/en/L02B",
                "name" : "XE P",
                "price" : "1234.0"
            },
            {
                "key" : "LVL004",
                "dataPath" : "/toy/in/en/L02B",
                "name" : "XE P",
                "price" : "1234.0"
            }

        ]
    }
}

现在我想检索一个只有一个等级为LVL001的完整文档。但是,当我查询这个时,

db.getCollection('models').find({$and: [{"dataPath" : "/nissan/in/en/L02B" }, {"grades.grades" : {$elemMatch: {"key":"LVL002"}}}]})

我得到了所有成绩。

我已经检查了帖子Retrieve Queried Element,但没有收到它。

我的代码使用的是Spring @Query。任何json查询参数也都很有用。

1 个答案:

答案 0 :(得分:1)

使用Mongo 2.2+,您可以使用新的Aggregation Framework

db.getCollection('models').aggregate([
    { $unwind : "$grades.grades" },
    { $match : {"dataPath": "/nissan/in/en/L02B", 
                "grades.grades.key": "LVL002"}}
])

Unwind从输入解构数组字段,为每个元素输出文档。使用您发布的文档作为示例,通过展开,您将有4个文档。然后使用match,您只需过滤所需的文档。

相关问题