MongoDB与列表数据聚合

时间:2018-02-01 07:04:36

标签: mongodb join mongodb-query aggregate

我需要使用mongodb聚合将数据分组。这是我在集合中的数据

[
    {
        bookName: "aaaa",
        bookNo: "1",
        registeredDate: "2018-02-01T06:51:16.738Z"
    },
    {
        bookName: "bbbb",
        bookNo: "2",
        registeredDate: "2018-02-01T06:51:29.244Z"
    }
    {
        bookName: "cccc",
        bookNo: "1",
        registeredDate: "2018-02-01T06:51:29.244Z"
    }
    {
        bookName: "dddd",
        bookNo: "2",
        registeredDate: "2018-02-01T06:51:29.244Z"
    }
]

我需要将上述数据聚合到group by中,并显示组内的数据。这是我需要的输出,

{
    Books: [
        {
        bookNo: "1",
            books: [{
                    bookName: "aaaa",
                    registeredDate: "2018-02-01T06:51:16.738Z"
                },
                {
                    bookName: "cccc",
                    registeredDate: ""2018-02-01T06:51:29.244Z"
                }]
        },
        {
        bookNo: "2",
            books: [{
                bookName: "bbbb",
                registeredDate: "2018-02-01T06:51:29.244Z"
            },
            {
                bookName: "dddd",
                registeredDate: "2018-02-01T06:51:29.244Z"
            }]
        }
    ]
}

有人帮我找到解决方案。

先谢谢,

2 个答案:

答案 0 :(得分:3)

尝试以下聚合:

db.books.aggregate([
    {
        $group: {
            _id: "$bookNo",
            books: {
                $push: {
                    bookName: "$bookName",
                    registeredDate: "$registeredDate"
                }
            }
        }
    },
    {
        $project:{
            _id: 0,
            bookNo: "$_id",
            books: 1
        }
    }
])

$group中,您可以指定每个文档中的$pushed字段。然后,您可以使用$project_id重命名为bookNo字段

答案 1 :(得分:0)

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
                _id: '$bookNo',
                //Books:{$addToSet:{bookNo:'$bookNo'}},
                books: {
                    $addToSet: {
                        bookname: '$bookName',
                        registeredDate: '$registeredDate'
                    }
                },

            }
        },

        // Stage 2
        {
            $group: {
                _id: null,
                Books: {
                    $addToSet: {
                        books: '$books',
                        bookNo: '$_id'
                    }
                }
            }
        },

        // Stage 3
        {
            $project: {
                _id: 0,
                Books: 1
            }
        }

    ]


);