1

タグの数でソートされた出版物のリストを取得しようとしています。私はいくつかの作業を行っていますが、$unwindオペレーターはタグのない出版物を消し去ります。私は成功せずにそれをバイパスするためにプレースホルダーを追加しようとしました:

Publication.collection.aggregate(
    { "$project" => { tags: { "$push" => "holder" } } }, 
    { "$unwind" => '$tags' }, 
    { "$group" => { _id: '$_id', count: { "$sum" => 1 } } }, 
    { "$sort" => { count: 1 } }
  )

私が得た:

failed with error 15999: "exception: invalid operator '$push'"

ドキュメントの例:

{ _id: '1', tags: ['b','c'] } 
{ _id: '2', tags: ['a'] } 
{ _id: '3' }

何か案は?

4

1 に答える 1

2

パイプライン ステージ$pushでは使用できません。舞台$project専用です。$group残念ながら、集計パイプラインのすべてのタグ配列の末尾に定数を追加することはできません。

これはエレガントではありませんが、コレクション自体のすべてのタグ配列にプレースホルダーを追加します。

db.collection.update({}, {$addToSet: {tags: null}}, false, true)

次に、パイプラインの最後でカウントから 1 を引きます。

db.collection.aggregate(
    { '$unwind' : '$tags' },
    { '$group' : { _id: '$_id', count: { '$sum' : 1 } } },
    { $project: { _id: true, count: { '$subtract': [ '$count', 1 ] } } },
    { '$sort' : { count: 1 } }
)

https://jira.mongodb.org/browse/SERVER-9334に投票して、将来的により良い方法を取得してください。

于 2013-05-30T17:10:36.593 に答える