0

我的数据有这样的结构:

{
    "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 中查询它

任何帮助,将不胜感激。先感谢您。

4

2 回答 2

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
}
于 2013-06-23T16:10:11.307 回答
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})

将上面的 (skip, limit) 的 (0, 2) 更改为下一组 2。

于 2013-06-20T20:16:45.320 回答