【问题标题】:min value of field in array and 1st object in array mongodb aggregation query数组中字段的最小值和数组mongodb聚合查询中的第一个对象
【发布时间】:2016-01-24 13:12:51
【问题描述】:

让我使用以下伪示例来更好地解释我的需求。

我有一群人和一些属于组模式的图像

{
  images:['ARRAY OF IMAGES'],
  members:[{
    age:NUMBER,
    name:STRING, 
    email:EMAIL_OF_MEMBER
  }], 
  groupName:String
  ....etc
}

现在我有一个聚合查询

group.aggregate([
  {
    $project:{
       //some code happening to support query in the below $match
       'original':$$ROOT
    }
  },
  {
    $match:{//some query code happening and all params from $project above will be available here.  the $original field contains all fields of document}
  },
  {
    //Now i want to extract 1st image from Images array, Min and Max age of members in group.
  }
],function(err,results){//dosomething with results})

如果我不使用第三个管道,我将获得我不需要的整个文档。我只需要一组人的 1 张图片和最小最大年龄来显示网页。我不需要其他细节。

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query


    【解决方案1】:

    查询的以下部分将为您提供第一张图片以及成员的最小和最大年龄。

    db.[collection].aggregate([
                                { 
                                  $unwind : "$members" 
                                },
                                { 
                                  $group : 
                                         { _id: "$_id" , 
                                           images : { $first: "$images"},
                                           minAge : {$min : "$members.age"},
                                           maxAge : {$max: "$members.age"}
                                         }
                                }
                              ]).pretty();
    

    mongoDb Version 3.1.6及以上版本,可以在聚合管道中使用$Slice来限制数组的内容。

    db.[collection].aggregate([
                                { 
                                  $unwind : "$members" 
                                },
                                { 
                                  $group : 
                                         { _id: "$_id" , 
                                           images : {$push : "$images"},
                                           minAge : {$min : "$members.age"},
                                           maxAge : {$max: "$members.age"}
                                         }
                                },
                                { 
                                  $project : 
                                           { images : 
                                               { images :{$slice:1} }
                                           },
                                           minAge : 1 ,
                                           maxAge  : 1
                               }
                             ]).pretty();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2021-12-09
      • 2021-08-13
      • 1970-01-01
      • 2021-01-09
      • 2020-07-24
      相关资源
      最近更新 更多