Querying subdocuments for specific categories and quantity greater than 0

I have the following schema for an e-commerce clothing shop:

{{{
// Define the schema for the data
const ProductSchema = new mongoose.Schema({
name: String,
description: String, //client description of their product
category: { type: String, enum: productCategories},//shirt, t shirt,
material: String, //jean, cotton, ect
colors:[
{
color: String, //dark wash/ medium wash
sizes:[{
size: String,
inseams:[{
image: String,
inseam: Number,
price: Number,
stock: Number,
}]
}]
}
],

});
}}}
And I want to return a cursor to all the items that fit a specific color and category, say “Jeans” and “Medium wash”, but also only pointing to documents that have stock greater than 0.

If possible, I would later like to edit that cursor to return the subdocument that matches the color, size, and specific inseam the costumer requests.

I’m struggling a lot to build a query, it seems I need to use some form of aggregation but I’m really at a loss here-- I just started using MongoDB

As requested in your other post Querying subdocuments to find all that have a greater quantity than 0

Sorry, i can’t seem to figure out how to format code in these forms, but I figured out my question!

I made the following aggregation queries:

//just for specified color
db.maindb.aggregate([{$unwind : “$colors”},{$match : {category:“jean”, “colors.color”: “Medium wash”}},{$project : {_id : 1,
name: 1,
color : “$colors.color”,
image: “$colors.image”,
sizes : “$colors.sizes”}},
{ $out : ‘aggResults’ }]).pretty()

//color and size
db.maindb.aggregate([{$unwind : “$colors”},{$match : {category:“jean”, “colors.color”: “Medium wash”}},{$project : {_id : 1,
name: 1,
color : “$colors.color”,
image: “$colors.image”,
sizes : “$colors.sizes”}},
{$unwind : “$sizes”},{$match : {“sizes.size”:“m”}},{$project : {_id : 1,
name: 1,
color : 1,
image: 1,
size : “$sizes.size”,
inseams:“$sizes.inseams”}},{ $out : ‘aggResults’ }]).pretty()

//color, size, and inseam
db.maindb.aggregate([{$unwind : “$colors”},{$match : {category:“jean”, “colors.color”: “Medium wash”}},{$project : {_id : 1,
name: 1,
color : “$colors.color”,
image: “$colors.image”,
sizes : “$colors.sizes”}},
{$unwind : “$sizes”},{$match : {“sizes.size”:“m”}},{$project : {_id : 1,
name: 1,
color : 1,
size : “$sizes.size”,
inseams:“$sizes.inseams”}},
{$unwind : “$inseams”},{$match : {“inseams.inseam”:28}},{$project : {_id : 1,
name: 1,
color : 1,
image: 1,
size : 1,
inseam:“$inseams.inseam”,
price:“$inseams.price”,
stock:“$inseams.stock”}}
,{ $out : ‘aggResults’ }]).pretty()

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.