Reputation: 355
I'm learning MongoDB and trying to retrieve objects by a specific key value using MongoDB client.
I have this data:
{
"type": "products",
"products": {
"Intel® Core™ i9-9980XE Extreme Edition": {
"description": null,
"price": 2457,
"catalog_id": "1"
},
"Intel® Core™ i9-9980HK": {
"description": null,
"price": 1548,
"catalog_id": "1"
},
"AMD Ryzen Threadripper 2990WX": {
"description": null,
"price": 500,
"catalog_id": "2"
},
"Baikalel Ectronics BE-M1000": {
"description": null,
"price": 128,
"catalog_id": "3"
},
"GeForce RTX 2080 Ti": {
"description": null,
"price": 2048,
"catalog_id": "5"
}
}
}
I've find out how to access to data in nested objects:
db.shop.findOne( { type : "products" }).products["GeForce RTX 2080 Ti"].price
But I'm a little bit confused how to get all hested objects filtred by "catalog_id": "1"
When I use
db.shop.find( { type : "products" }, {"catalog_id": "1"})
MongoDB client shows only id of the main object.
Upvotes: 1
Views: 551
Reputation: 130
The data you have shared here looks like a single object only, with having two keys type and products. So your query is matching this object and returning you the object correctly. You need to parse it afterwards. Mongo query will only give you records only.
{
**"_id": ObjectId("58c7da2adaa8d031ea699fff")**
"type": "products",
"products": {
"Intel® Core™ i9-9980XE Extreme Edition": {
"description": null,
"price": 2457,
"catalog_id": "1"
},
"Intel® Core™ i9-9980HK": {
"description": null,
"price": 1548,
"catalog_id": "1"
},
"AMD Ryzen Threadripper 2990WX": {
"description": null,
"price": 500,
"catalog_id": "2"
},
"Baikalel Ectronics BE-M1000": {
"description": null,
"price": 128,
"catalog_id": "3"
},
"GeForce RTX 2080 Ti": {
"description": null,
"price": 2048,
"catalog_id": "5"
}
}
}
Upvotes: 0
Reputation: 69
db.shop.find( { "products.catalog_id": "1"})
Similiar question MongoDB: How to find a document by an id inside a nested document
Upvotes: 1