使用mongo聚合框架按数组的特定元素进行分组

Rus*_*ell 8 mongodb aggregation-framework

是否可以使用聚合框架按数组的特定元素进行分组?

这样的文件就像这样:

{
  name: 'Russell',
  favourite_foods: [
    { name: 'Pizza', type: 'Four Cheeses' },
    { name: 'Burger', type: 'Veggie'}
  ],
  height: 6
}
Run Code Online (Sandbox Code Playgroud)

我可以得到一份独特的最受欢迎的食物清单(即0号食物)以及最受欢迎食物的最高人物的高度?

像这样的东西(尽管它不起作用,因为数组索引访问点表示法似乎在聚合框架中不起作用):

db.people.aggregate([
  { $group : { _id: "$favourite_foods.0.name", max_height: { $max : "$height" } } }
])
Run Code Online (Sandbox Code Playgroud)

Asy*_*sky 15

看起来你依赖于每个人在阵列中的第一个最喜欢的食物.如果是这样,您可以利用聚合框架运算符.

这是您可以使用的管道:

db.people.aggregate(
[
    {
        "$unwind" : "$favourite_foods"
    },
    {
        "$group" : {
            "_id" : {
                "name" : "$name",
                "height" : "$height"
            },
            "faveFood" : {
                "$first" : "$favourite_foods"
            }
        }
    },
    {
        "$group" : {
            "_id" : "$faveFood.name",
            "height" : {
                "$max" : "$_id.height"
            }
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

在此示例数据集上:

> db.people.find().pretty()
{
    "_id" : ObjectId("508894efd4197aa2b9490741"),
    "name" : "Russell",
    "favourite_foods" : [
        {
            "name" : "Pizza",
            "type" : "Four Cheeses"
        },
        {
            "name" : "Burger",
            "type" : "Veggie"
        }
    ],
    "height" : 6
}
{
    "_id" : ObjectId("5088950bd4197aa2b9490742"),
    "name" : "Lucy",
    "favourite_foods" : [
        {
            "name" : "Pasta",
            "type" : "Four Cheeses"
        },
        {
            "name" : "Burger",
            "type" : "Veggie"
        }
    ],
    "height" : 5.5
}
{
    "_id" : ObjectId("5088951dd4197aa2b9490743"),
    "name" : "Landy",
    "favourite_foods" : [
        {
            "name" : "Pizza",
            "type" : "Four Cheeses"
        },
        {
            "name" : "Pizza",
            "type" : "Veggie"
        }
    ],
    "height" : 5
}
{
    "_id" : ObjectId("50889541d4197aa2b9490744"),
    "name" : "Augie",
    "favourite_foods" : [
        {
            "name" : "Sushi",
            "type" : "Four Cheeses"
        },
        {
            "name" : "Pizza",
            "type" : "Veggie"
        }
    ],
    "height" : 6.2
}
Run Code Online (Sandbox Code Playgroud)

你得到这些结果:

{
    "result" : [
        {
            "_id" : "Pasta",
            "height" : 5.5
        },
        {
            "_id" : "Pizza",
            "height" : 6
        },
        {
            "_id" : "Sushi",
            "height" : 6.2
        }
    ],
    "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*yHK 5

看起来目前无法在聚合中从数组中提取特定元素:https: //jira.mongodb.org/browse/SERVER-4589