如何在MongoDb中进行部分查询

时间:2013-06-20 19:15:07

标签: mongodb partial

我的数据有这样的结构:

{
    "user": {
        "name":"John",
        "sports":[
            {"sId":"sport1","name":"basketball"},
            {"sId":"sport2",{"name":"tennis"},
            {"sId":"sport3","name":"surf"}, ...
            {"sId":"sportN","name":"golf"}
        ],
        "birthDate":"25/07/1960"
    }
}

我希望过滤以获得相同的用户,但仅限于两项首次运动,例如:

{
    "user": {
        "name":"John",
        "sports":[
            {"sId":"sport1","name":"basketball"},
            {"sId":"sport2","name":"tennis"}
        ],
        "birthDate":"25/07/1960"
    }
}

然后是接下来的两个,......

{
    "user": {
        "name":"John",
         "sports":[
            {"sId":"sport3","name":"surf"},
            {"sId":"sport4","name":"icehockey"}
        ],
        "birthDate":"25/07/1960"
    }
}

诸如此类

但我不知道如何在没有获得整个用户的情况下在mongo中查询

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

作为替代方案,您可以稍后将结果分组,以便以正常格式恢复两项运动:

db.so.aggregate(
    {$match : {'user.name':'John'}},
    {$unwind : '$user.sports'},
    {$skip: 0},
    {$limit : 2},
    {$group: {
        _id: '$_id', 
        name: { $first: '$user.name' }, 
        sports: { $push: '$user.sports' }, 
        birthDate: { $first: '$user.birthDate' }
    } }
);

然后输出:

{
    "result" : [
        {
            "_id" : ObjectId("51c71c8d4a01738f3eac69fc"),
            "name" : "John",
            "sports" : [
            {
                    "sId" : "sport1",
                    "name" : "basketball"
                },
                {
                    "sId" : "sport2",
                    "name" : "tennis"
                }
            ],
            "birthDate" : "25/07/1960"
        }
    ],
    "ok" : 1
}

答案 1 :(得分:0)

一种替代方案可以是使用聚合框架:

db.testing.aggregate({$match : {'user.name':'John'}},{$unwind : '$user.sports'}, {$skip: 0}, {$limit : 2})
db.testing.aggregate({$match : {'user.name':'John'}},{$unwind : '$user.sports'}, {$skip: 2}, {$limit : 4})

更改(0,2)for(skip,limit)以获得下一组2。