sails.js - Fetch distinct record based on values for that record with MongoDB -


i have collection of restaurant record .some of restaurant in collection belongs group(chain type restaurant eg. kfc etc) while other doesn't has group(individual restaurant ,that doesn't belongs chain).

example :

restaurant collections

{_id:"1",title:"rest1",address:"somethingx",chain_id:"123"}, {_id:"2",title:"rest2",address:"somethingx",chain_id:"123"}, {_id:"3",title:"rest3",address:"somethingy",chain_id:"0"}, {_id:"4",title:"rest4",address:"somethingx",chain_id:"0"}  

chain collection :

{_id:"123",chain_name:"vsweets",address_deatils:[                                           {restid:"",address:"somethingx"},                                           {restid:"",address:"somethingx"}                                          ] }  {_id:"456",chain_name:"kfc",address_deatils:[]} 

i need fetch distinct restaurant similiar chain_id, i.e, single restaurant should come if belongs chain(chain_id !=0)

you use aggregation framework this. aggregation pipeline have first step $match operator filters restaurants on address. $group pipeline stage group filtered documents chain_id key , applies accumulator expression $first $$root system variable on each group. can reshape documents using $project pipeline stage.

the final aggregation pipeline gives desired results follows:

db.restaurant.aggregate([     {         "$match": { "address" : "somethingx" }     },     {         "$group": {             "_id": "$chain_id",             "data": { "$first": "$$root" }         }     },     {         "$project": {             "_id" : "$data._id",             "title" : "$data.title",             "address" : "$data.address",             "chain_id" : "$data.chain_id"         }     } ]) 

output:

/* 0 */ {     "result" : [          {             "_id" : "4",             "title" : "rest4",             "address" : "somethingx",             "chain_id" : "0"         },          {             "_id" : "1",             "title" : "rest1",             "address" : "somethingx",             "chain_id" : "123"         }     ],     "ok" : 1 } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -