glebiuskv
glebiuskv

Reputation: 331

How to find mongo document by parrameter in internal map (better with Spring MongoTemplate)

I have collection with docs:

{
    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}
      }
}

How i can find document, which contains c == 5? In my case:

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

P.S. I use Spring MongoTemplate in my app. And it will be better to see MongoTemplate usage in answer.

Upvotes: 1

Views: 343

Answers (1)

TomG
TomG

Reputation: 2539

This can't be done using pure mongo, I suggest to change the schema. But this can be done using $where:

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

Upvotes: 3

Related Questions