Mongodb - 查询数组中的子文档

时间:2016-04-06 10:54:32

标签: mongodb

使用mongodb 3.0 - 如果我有这样的文档(简单版本):

{
    "_id" : "1",
    "Name" : "Bob",
    "Timestamp" : ISODate("2016-02-22T14:05:04.000Z"),
    "SportingHobbies" : [ 
        {
            "Sport" : "Football",
            "Position" : "Forward",
            "SkillLevel" : 6,
        }, 
        {
            "Sport" : "Football",
            "Position" : "Defender",
            "SkillLevel" : 3,
        }, 
        {
            "Sport" : "Hockey",
            "Position" : "Forward",
            "SkillLevel" : 5,
        }
    ]
}

我正在尝试为特定的一组标准获取SkillLevel。我尝试了以下方法:

db.test.find(
    {    
        "Name" : "Bob",
        "Timestamp": {$gte : ISODate('2016-02-22T14:00:00.000Z'), $lte : ISODate('2016-02-22T15:00:00.000Z')},
        "SportingHobbies" : {$elemMatch : {"Sport" : "Football", "Position" : "Forward"}}
    },
    {
        _id: 0,
        'SportingHobbies.$' : 1
    }
    );

我得到的结果是:

{
    "SportingHobbies" : [ 
        {
            "Sport" : "Football",
            "Position" : "Forward",
            "SkillLevel" : 6,
        }
    ]
}

我只想要SkillLevel值 - “SkillLevel”:“6”

我也尝试过:

db.test.find(
    {    
        "Name" : "Bob",
        "Timestamp": {$gte : ISODate('2016-02-22T14:00:00.000Z'), $lte : ISODate('2016-02-22T15:00:00.000Z')},
        "SportingHobbies.Sport" : "Football", 
        "SportingHobbies.Position" : "Forward"
    },
    {
       _id: 0,
        "SportingHobbies.SkillLevel" : 1
    }
    );

但这会带回所有技能等级。结果:

{
    "SportingHobbies" : [ 
        {
            "SkillLevel" : "6"
        }, 
        {
            "SkillLevel" : "3"
        }, 
        {
            "SkillLevel" : "5"
        }
    ]
}

我是在正确的轨道上吗?

这是我最接近的:

var printData = function(doc){
        print(doc.SportingHobbies.SkillLevel);    {
    "SportingHobbies" : [ 
        {
            "Sport" : "Football",
            "Position" : "Forward",
            "SkillLevel" : 6,
        }
    ]
}
    }

var cursor = db.test.aggregate([
    {$match: {    
        "Name" : "Bob",
        "Timestamp": {$gte : ISODate('2016-02-22T14:00:00.000Z'), $lte : ISODate('2016-02-22T15:00:00.000Z')},
        "SportingHobbies" : {$elemMatch : {"Sport" : "Football", "Position" : "Forward"}}
    }},
    {$unwind: '$SportingHobbies'}
    ]);

cursor.forEach(printData);

但结果又是:

6
3
5

我不希望我的结果是这样的集合:

{
    "SportingHobbies" : [ 
        {
            "Sport" : "Football",
            "Position" : "Forward",
            "SkillLevel" : 6,
        }
    ]
}

我希望我的结果是6。

0 个答案:

没有答案