0

集約フレームワークを介してさまざまなドキュメントをパイプした後、最終的に結果のドキュメントが得られます。

今の問題は、$first と $last のドキュメントだけが欲しいということです。

最終的なドキュメントは次のようになります (膨大なリスト)。

            ...
            {
                    "_id" : "Kaila Deibler",
                    "count" : 406
            },
            {
                    "_id" : "Jessika Dagenais",
                    "count" : 406
            },
            {
                    "_id" : "Tamika Schildgen",
                    "count" : 404
            },
            ...

ドキュメントの作成に使用した mongo シェル コマンドは次のとおりです。
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}])

しかし、最初と最後のドキュメントだけが必要なので、次のようなことを試みました:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$first: "$_id"}])

私は他の実装を試しましたが、いつ/どこで実装するかを理解できないよう$firstです$last

助言がありますか?

4

2 に答える 2

1

$first$lastはパイプラインの集計関数です。つまり、ドキュメント$group内で使用する必要があります。$group

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}, first: {$first:"$_id"}}}, {$sort: {count: -1}}])

同様に$last

これを示す例をここで見つけることができます

于 2012-12-03T21:17:07.000 に答える
0

この質問に対する私自身の答えは次のとおりです。

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$group: {_id: "$_id.comments.author", first: {$first: "$_id"}, last: {$last: "_id"}}}])

ソート後に最初と最後のドキュメントを取得したいので、別のドキュメントを適用する必要が$groupあり$firstます$last。結果:

{
        "result" : [
                {
                        "_id" : null,
                        "first" : "Elizabet Kleine",
                        "last" : "Mariela Sherer"
                }
        ],
        "ok" : 1
}

に注意してください"_id" : null。これは必要ですか?
誰かがより良い解決策を持っている場合は、共有してください。

于 2012-12-03T21:55:45.783 に答える