通过嵌套文档查询MongoDB并仅显示特定变量

时间:2017-11-22 15:28:44

标签: mongodb

我有包含嵌套数组的文档,如下所示:

  1. {"data": [{"Measure": "Temperature","value" : 10},{"Measure": "Humidity","value" : 10}],"date" : ISODate("2017-11-22T00:30:48.257Z")}

  2. {"data": [{"Measure": "Temperature","value" : 15},{"Measure": "Humidity","value" : 15}],"date" : ISODate("2017-11-22T00:31:23.215Z")}

  3. 我已完成db.collection.find({'data.Measure':'Temperature'}, {'data.$':1, 'date':1}),结果显示:

    [{
        "data" : [{
                "Measure": "Temperature",
                "value" : 10
        }],
            "date" : ISODate("2017-11-22T00:30:48.257Z")
    },{
        "data" : [{
                "Measure": "Temperature",
                "value" : 15
            }],
        "date" : ISODate("2017-11-22T00:31:23.215Z")
    }]
    

    实际上,我想查询Measure:Temperature作为结果:

    [{
        "Measure": "Temperature",
        "value" : 5,
        "date" : ISODate("2017-11-22T00:30:48.257Z")
    }, {
        "Measure": "Temperature",
        "value" : 15,
        "date" : ISODate("2017-11-22T00:31:23.215Z")
    }]
    

    我可以查询并获得这样的结果吗?

1 个答案:

答案 0 :(得分:0)

您可以使用聚合管道来获取上述结果。要获得结果,您必须使用$ unwind聚合,然后$匹配条件,然后在项目结果之后。请阅读MongoDb Aggregation$unwind以及$match

的文档

我已为您准备好查询:

private void Room15()
{
    if(player.hasItemInInventory("Sword"))
    {
        System.out.println("Congratulations! You won the game and your freedom!");
    }
    else {
        System.out.println("Hurry back and find a sword!!!");
    }  
}