Node.JS + MongoDB aggregation Find array in array from database to MongoDB
I have a model in MongoDB that includes an array (category) that has an array (image) inside it. The shirt model looks like this:
{ _id: 100, category: [ { name: 'CatName', _id: 101, picture: [Object] } ] }
And my array of images looks like this:
[ { path: 'p1', _id: 102 },
{ path: 'p2', _id: 103 } ] }
Passing 3 variables
- main array id which is 100 (var1)
- category name directory_name (var2)
- Image ID 102 (var3)
I want to get an array that looks like this:
{ _id: 100, category: [ { name: 'CatName', _id: 101,
picture: [ { path: 'p1', _id: 102 }]
} ]
}
I've tried this:
Shirt.find( {_id: var1} ,
{category: { $and:[ { name: var2 } , { picture: {$elemMatch: {_id: var3}}} ] }} )
.exec(function(err, product) {
console.log('Result ' + product );
res.jsonp(product);
});
But the result I get is Undefined for the first code
Second code I tried:
Shirt.find( {_id: var1} ,
{category: {$elemMatch: { name: var2,picture: {$elemMatch: {_id: var3} }}} } )
And the result from the second code is filtering the array for var1 and var2 But it contains the whole array of images, which means it doesn't filter var3
- What is the correct code to find what I want?
- Is this the correct fit for the store's website database? Or do you have a better offer?
- Am I using the parent and child databases correctly?
Thank!
source to share
After a mongo query, you will get the expected result:
db.collection.find({
"category": {
$elemMatch: {
"name": "CatName",
"picture": {
$elemMatch: {
"_id": 102
}
}
}
}
})
You need to convert it to node.js format.
The following format might help you. Not tested
collection.find({
_id: "" // add your match Id here} ,
{
category: {
"$elemMatch": {
"name": "CatName",
"picture": {
$elemMatch: {
"_id": 102
}
}
}
}
}
})
.exec(function(err, product) {
console.log('Result ' + product);
res.jsonp(product);
});
AFTER THE QUESTION CHANGE
You have to use mongo aggregation to get the values โโyou want . The request will look like this:
db.collection.aggregate({
$unwind: '$category'
}, {
$unwind: '$category.picture'
}, {
$match: {
_id: 100, // add here your var1 variable instead of 100
'category.name': 'CatName', // add here your var2 variable instead of 'CatName'
'category._id': 102, //add your match id here if any otherwise remove this condition
'category.picture._id': 102 //add your var3 instead of 102
}
}, {
$group: {
_id: '$category.name',
'name': {
$first: '$category.name'
},
'picture': {
'$push': '$category.picture'
}
}
})
source to share