MongoDb查询以获取数组中字段的最大值 [英] MongoDb query to get max of field inside array

查看:530
本文介绍了MongoDb查询以获取数组中字段的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取以下文档中的sections.id的最大值,其中collection._id =一些参数

How to get the maximum of sections.Id in below document where collection._id = some parameter

{
    "_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单个值,而是返回sections数组中所有Id的数组.

But instead of returning max int single value it is returning an array of all Ids in sections array.

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

Further same query when executed in node.js it returns an empty array.

推荐答案

您的聚合查询需要$unwind才能将opennig传输到"sections"数组

your aggregation query need $unwind for opennig to "sections" array

在此添加您的聚合查询

{$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/

and more knowledge for $unwind : https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

这篇关于MongoDb查询以获取数组中字段的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆