gwendall
gwendall

Reputation: 920

Query for any nested subdocuments

I would like to perform a query for a given nested value on multiple subdocuments.

In the example below, I would like to perform the search across multiple "product_types" objects.

{
  "product_types": {
    "type_1": [
      {
        name: "something",
        price: 100
      },
      {
        name: "something else",
        price: 50
      }
    ],
    "type_2": [
      {
        name: "another one",
        price: 20
      },
      {
        name: "and a last one",
        price: 30
      }
    ]
  }
}

I understood the dollar sign matches any subdocument. Here is what I came up with to get all the product with a "price" value of 100. But it doesn't work. Any idea?

db.inventory.find( { product_types.$.price : 100 } )

PS: I anticipate on some answers saying that such a db design to store products would be very bad and I agree; this is just an example to illustrate the kind of query I want to perform.

Upvotes: 0

Views: 1474

Answers (2)

Prem Yadav
Prem Yadav

Reputation: 1

Searching with embedded documents can be done as

db.inventory.find({"product_types.type_1.price":100})

Field name should be inside " "! Otherwise it will throw syntax error.

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311865

MongoDB doesn't support any sort of wildcard property like you're trying to do here with $. However, you can search multiple properties using an $or operator:

db.inventory.find({ $or: [
  { product_types.type_1.price: 100 },
  { product_types.type_2.price: 100 }
]})

But this is going to return the matching documents in full rather than just the matched array elements, so you'll also have to post-process the docs in your code to pull those out.

Upvotes: 2

Related Questions