Mongo:在关联数组中查找

时间:2015-04-09 08:15:52

标签: mongodb mongodb-query

我正在收集“播放器”,每个文档看起来都是这样的

{
    "player_id": 20,
    "level_details": {
        "12": {
            "is_completed": false,
            "level_data": "oijoisdffs",
            "completed_on": 1428570153
        },
        "13": {
            "is_completed": true,
            "level_data": "lfsdfjfjg",
            "completed_on": 1428512384
        },
        "14": {
            "is_completed": true,
            "level_data": "oafodjfosf",
            "completed_on": 1318374857
        },
        "15": {
            "is_completed": false,
            "level_data": "sdmflskfmm",
            "completed_on": 1428938475
        }
   }

}

我想对单个文档进行以下查询, “获取所有level_details,其player_id = 20且is_compelted = true且completed_on> = 1428512300和completed_on< = 1428512500”

所以,在回应中我期待像

这样的东西
{
"level_details": {
    "13": {
        "is_completed": true,
        "level_data": "lfsdfjfjg",
        "completed_on": 1428512384
    }
}
}

任何人都可以让我知道我该怎么做?

1 个答案:

答案 0 :(得分:1)

首先,你应该改变你的文件结构,如下所示

{
    "player_id": 20,
    "level_details": [
    {
        "is_completed": false,
        "level_data": "oijoisdffs",
        "completed_on": 1428570153
    },
    {
        "is_completed": true,
        "level_data": "lfsdfjfjg",
        "completed_on": 1428512384
    },
    {
        "is_completed": true,
        "level_data": "oafodjfosf",
        "completed_on": 1318374857
    },
    {
        "is_completed": false,
        "level_data": "sdmflskfmm",
        "completed_on": 1428938475
    }
    ]
}

现在根据您的要求,您应该使用两种方式找到结果

1>使用简单的find$elemMatch,如下所示

db.collectionName.find({
    "$and": [{
    "player_id": 20
    }, {
    "level_details": {
        "$elemMatch": {
            "completed_on": {
                "$gte": 1428512300
            }
        }
    }
    }, {
    "level_details": {
        "$elemMatch": {
            "completed_on": {
                "$lte": 1428512500
            }
        }
    }
    }, {
    "level_details": {
        "$elemMatch": {
            "is_completed": true
        }
    }
    }]
}, {
    "level_details.$": 1
}).pretty()

2 - ; Mongo aggrgation查询如下

db.collectionName.aggregate({
    "$unwind": "$level_details"
}, {
    "$match": {
    "$and": [{
        "player_id": 20
    }, {
        "level_details.completed_on": {
            "$gte": 1428512300
        }
    }, {
        "level_details.completed_on": {
            "$lte": 1428512500
        }
    }, {
        "level_details.is_completed": true
    }]
    }},
    {
   "$project": {
    "level_data": "$level_details.level_data", // Finding only level_data
    "_id": 0
    }
    }).pretty()