我正在尝试获取按标签数量排序的出版物列表。我已经做了一些工作,但是$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' }有什么想法吗?
发布于 2013-05-31 01:10:37
不能在$project管道阶段使用$push;它只能用于$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,让它在未来获得更好的方法。
https://stackoverflow.com/questions/16815251
复制相似问题