MindMincer
MindMincer

Reputation: 81

mongodb : how to get documents that contains nested field

How can i get documents that contains nested field f5=12?

db.products.insert( { f: "card", f1: {f2 : {f3 : 15 } } } )

db.products.insert( { f: "card", f1: {f2 : {f4 : {f5 : 12} } } } )

db.products.insert( { f: "card", f1: {f2 : {f3 : {f5 : 43} } } } )

db.products.insert( { f: "card", f1: {f2 : {f4 : 98 } } } )

I've tried smth like this:

db.products.find($where : "this.content.indexOf('f5 : 12') != -1")

db.products.find( {$elemMatch : {f5 : 12} })

But it doesn't work.. Does anyone has any ideas?

Upvotes: 1

Views: 378

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312095

You can use dot notation in your query to do this:

db.products.find({'f1.f2.f4.f5': 12})

If you want something more flexible where you don't have to specify each of the parent keys, you'd need to search the docs using a $where operator.

Upvotes: 1

Related Questions