2016-04-24 45 views
0

场的最大如何获得最大sections.Id以下文件,其中collection._id =一些参数MongoDB的查询来获取里面阵列

{ 
    "_id" : ObjectId("571c5c87faf473f40fd0317c"), 
    "name" : "test 1", 
    "sections" : [ 
     { 
      "Id" : 1, 
      "name" : "first section" 
     }, 
     { 
      "Id" : 2, 
      "name" : "section 2" 
     }, 
     { 
      "Id" : 3, 
      "name" : "section 3" 
     } 
} 

我曾尝试下面

db.collection.aggregate(
[ 
    { 
     "$match": { 
      "_id": ObjectId("571c5c87faf473f40fd0317c") 
     } 
    }, 
    { 
     "$group" : { 
      "_id" : "$_id", 
      "maxSectionId" : {"$max" : "$sections.Id"} 
     } 
    } 
]); 

但在不是返回max int single值,而是返回section数组中所有id的数组。

在node.js中执行更多相同的查询时,它将返回一个空数组。

回答

1

您的聚集查询需要$unwind为opennig到"sections"阵列

添加聚集查询此

{$unwind : "$sections"} 

和你的重构聚集这样的查询

db.collection.aggregate(
[ 
    {$unwind : "$sections"}, 
    { 
     "$match": { 
      "_id": ObjectId("571c5c87faf473f40fd0317c") 
     } 
    }, 
    { 
     "$group" : { 
      "_id" : "$_id", 
      "maxSectionId" : {"$max" : "$sections.Id"} 
     } 
    } 
]); 

$unwind更多的知识:https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

0

替换$组$项目

In the $group stage, if the expression resolves to an array, $max does not traverse the array and compares the array as a whole.

With a single expression as its operand, if the expression resolves to an array, $max traverses into the array to operate on the numerical elements of the array to return a single value [sic]

+0

使用$项目抛出异常:无效运算符“$最大”,代码15999 –

+0

什么版本的MongoDB是您使用......在这种情况下,请按照@kakashi hatake的说明使用展开,但在匹配查询后使用它来限制展开文档的数量 – kryshna

+0

MongoDB shell版本:3.0.7。我需要所有展开的部分的最大值,但是对于已经应用了过滤器的特定collection._id,因此无法对sections.Id应用过滤器。 –