简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM