Node.JS + MongoDB aggregation Find array in array from DataBase in MongoDB -


i have model in mongodb include array(category) has array(picture) inside it. shirt model looks this:

{ _id: 100, category: [ { name: 'catname', _id: 101, picture: [object] } ] } 

and picture array looks this:

 [ { path: 'p1', _id: 102 },    { path: 'p2', _id: 103 } ] } 

i pass 3 variables

  1. main array id 100 (var1)
  2. category name catname (var2)
  3. picture id 102 (var3)

i want array looks like:

{ _id: 100, category: [ { name: 'catname', _id: 101,                           picture: [ { path: 'p1', _id: 102 }]                           } ] } 

what have 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 result receive undefined first code

second code tried:

shirt.find( {_id: var1} ,             {category: {$elemmatch: { name: var2,picture: {$elemmatch: {_id: var3} }}} }  ) 

and result second code filter array var1 , var2 contain whole picture array means not filter var3

  1. what correct code find want?
  2. is correct approach shopping website database or have better suggestion?
  3. am applying parent , child database correctly?

thanks!

following mongo query give expected result:

db.collection.find({     "category": {     $elemmatch: {         "name": "catname",         "picture": {             $elemmatch: {                 "_id": 102             }         }     }     } }) 

you need convert in node.js format.

following format may you. not tested

collection.find({     _id: "" // add match id here} ,           {             category: {                 "$elemmatch": {                     "name": "catname",                     "picture": {                         $elemmatch: {                             "_id": 102                         }                     }                 }             }         }     })     .exec(function(err, product) {     console.log('result  ' + product);     res.jsonp(product);     }); 

after edit question

you should use mongo aggregation required values. query following -

db.collection.aggregate({     $unwind: '$category' }, {     $unwind: '$category.picture' }, {     $match: {     _id: 100, // add here var1 variable instead of 100     'category.name': 'catname', // add here var2 variable instead of 'catname'     'category._id': 102, //add match id here if otherwise remove condition     'category.picture._id': 102 //add var3 instead of 102     } }, {     $group: {     _id: '$category.name',     'name': {         $first: '$category.name'     },     'picture': {         '$push': '$category.picture'     }     } }) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -