MongoDb 查询以获取数组内字段的最大值 [英] MongoDb query to get max of field inside array
问题描述
如何在下面的文档中获取最大的sections.Id,其中collection._id = some parameter
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 单个值,而是返回部分数组中所有 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
for opennig to "sections"
数组
your aggregation query need $unwind
for opennig to "sections"
array
添加您的聚合查询
{$unwind : "$sections"}
和你这样的重构聚合查询
and your refactoring aggregation query like this
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屋!