如何在内部地图中通过参数找到mongo文档(更好地使用Spring MongoTemplate)

时间:2016-10-05 15:13:35

标签: java spring mongodb spring-data-mongodb

我收藏了文档:

{
    a:"a1",
    b:{
       "bla1-1":{c:1,d:2},
       "bla1-2":{c:3,d:4}
      }
},
{
    a:"a2",
    b:{
       "bla2-1":{c:1,d:2},
       "bla2-2":{c:5,d:6}
      }
}

我如何找到包含c == 5的文档?就我而言:

{
    a:"a2",
    b:{
       "bla2-1":{c:1,d:2},
       "bla2-2":{c:5,d:6}
    }
}

P.S。我在我的应用程序中使用Spring MongoTemplate 。最好看看MongoTemplate的使用方法。

1 个答案:

答案 0 :(得分:3)

使用纯mongo无法做到这一点,我建议更改架构。 但这可以使用$where

来完成
db.test.find({
    $where: function () {
        for (var prop in this.b) {
            if (this.b[prop].c == 5) {
                return true;
            }
        }
        return false;
    }
})