2016-12-17 3 views
1

Документ - Документ состоит из данных о населении, грамотных данных.Как свести к одному документу в финальной стадии агрегирования mongodb?

{ 
    "_id" : NumberInt(0), 
    "area" : "India", 
    "population" : { 
     "density" : NumberInt(382), 
     "class" : [ 
      { 
       "rural" : [ 
        { 
         "male" : [ 
          NumberInt(61285192), 
          NumberInt(427917052) 
         ] 
        }, 
        { 
         "female" : [ 
          NumberInt(56300322), 
          NumberInt(405170610) 
         ] 
        } 
       ] 
      }, 
      { 
       "urban" : [ 
        { 
         "male" : [ 
          NumberInt(21666943), 
          NumberInt(195807196) 
         ] 
        }, 
        { 
         "female" : [ 
          NumberInt(19536830), 
          NumberInt(181298564) 
         ] 
        } 
       ] 
      } 
     ] 
    }, 
    "education" : { 
     "class" : [ 
      { 
       "rural" : [ 
        { 
         "male" : NumberInt(288047480) 
        }, 
        { 
         "female" : NumberInt(204973398) 
        } 
       ] 
      }, 
      { 
       "urban" : [ 
        { 
         "male" : NumberInt(204973398) 
        }, 
        { 
         "female" : NumberInt(129276960) 
        } 
       ] 
      } 
     ] 
    } 
} 

Агрегация запросы - Пытаясь выяснить nodejs запроса, который поможет создать единый документ (JSON), содержащую информацию о ид, площади, плотности, мужских и женских данных данных. Ниже запрос генерирует два документа. Как объединить два документа в одном документе

router.get('/population/:id', function (req, res, next) { 
     var id = Number(req.params.id); 
     sCollection.aggregate(
      { 
       $match: { _id: id } 
      }, 
      { 
       $unwind: '$population.class' 
      }, 
      { 
       $unwind: '$population.class.rural' 
      }, 
      { 
       $project: { _id: '$_id', area: '$area', density: '$population.density', ruralMale: '$population.class.rural.male', ruralFemale: '$population.class.rural.female' } 
      }, 
      ).toArray(function (err, population) { 
       if (err) { 
        res.send('Error census-population not found ' + err); 
       } else { 

        res.json(population); 
       } 
      }); 
    }); 

Overall Aggregation Flow - Прикрепленный изображение поможет лучшему пониманию вопроса

+0

http://stackoverflow.com/a/40732823/2683814 Посмотрите, поможет ли это. – Veeram

ответ

0

вам нужно использовать $ группы, как это:

[ 
    {$match: { _id: 0 }}, 
    {$unwind: '$population.class'}, 
    {$unwind: '$population.class.rural'}, 
    {$group:{_id:"$_id", area: {$first: "$area"}, density: {$first:'$population.density'}, ruralMale: {$first: '$population.class.rural.male'}, ruralFemale: {$last:'$population.class.rural.female' }}} 

]

Смежные вопросы