在数组MongoDB中的所有文档上使用$ size

时间:2015-01-11 23:10:17

标签: mongodb mongodb-query aggregation-framework

这是我收藏的结构部分:

_id: ObjectId("W"),
names: [
    {
        number: 1,
        list: ["A","B","C"]
    },
    {
        number: 2,
        list: ["B"]
    },
    {
        number: 3,
        list: ["A","C"]
    }
    ...
],
...

我使用此请求:

db.publication.aggregate( [ { $match: { _id: ObjectId("54a1de90453d224e80f5fc60") } }, { $group: { _id: "$_id", SizeName: { $first: { $size: { $ifNull: [ "$names", [] ] } } }, names: { $first: "$names" } } } ] );

但我现在在名称数组的每个文档中使用 $ size

是否可以获得此结果(" sizeList "是 $ size 的结果):

_id: ObjectId("W"),
SizeName: 3,
names: [
    {
        SizeList: 3,
        number: 1,
        list: ["A","B","C"]
    },
    {
        SizeList: 1,
        number: 2,
        list: ["B"]
    },
    {
        SizeList: 2,
        number: 3,
        list: ["A","C"]
    }
    ...
],
...

2 个答案:

答案 0 :(得分:4)

你真正想要的是$project阶段并使用$map来改变数组成员的内容:

db.names.aggregate([
    { "$project": {
        "SizeName": { "$size": "$names" },
        "names": { "$map": {
            "input": "$names",
            "as": "el",
            "in": {
                "SizeList": { "$size": "$$el.list" },
                "number": "$$el.number",
                "list": "$$el.list"
            }
        }}
    }}
])

您可以选择使用 $unwind 进行处理,然后将其全部归还,但是当您拥有MongoDB 2.6时,这种情况会很长。

答案 1 :(得分:0)

这不一定是最有效的方式,但我认为它符合您的目标:

db.publication.aggregate( [ 
    { $unwind: '$names' },
    { $unwind: '$names.list' },
    { $group: {
        _id: { _id: "$_id", number: "$names.number" },
        SizeList: { $sum: 1 },
        list: { $push: "$names.list" }
      }
    },
    { $group: {
        _id: "$_id._id",
        names: {
            $push: {
                number: "$_id.number",
                list: "$list",
                SizeList: "$SizeList"
            }
        },
        SizeName: {$sum: 1}
      }
    }
]);