Javascript `$group`按数组中的唯一项排列
假设我们有这样的文件Javascript `$group`按数组中的唯一项排列,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,假设我们有这样的文件 [ {tags: ['a', 'b', 'c']}, {tags: ['b', 'c', 'd']} ] 那么我们如何计算每个标记的文档数呢 [ {_id: 'a', count: 1}, {_id: 'b', count: 2}, {_id: 'c', count: 2}, {_id: 'd', count: 1} ] 因为在$tags上执行正常的$group会(当然)给出不同的结果。我认为下面的查询将得到结果$REWIND是此处的关键 db.collec
[
{tags: ['a', 'b', 'c']},
{tags: ['b', 'c', 'd']}
]
那么我们如何计算每个标记的文档数呢
[
{_id: 'a', count: 1},
{_id: 'b', count: 2},
{_id: 'c', count: 2},
{_id: 'd', count: 1}
]
因为在
$tags
上执行正常的$group
会(当然)给出不同的结果。我认为下面的查询将得到结果<代码>$REWIND是此处的关键
db.collection_name.aggregate( [ { $unwind : "$tags" },
{ $group : { _id : "$tags", total : { $sum : 1 } } }] )
作为参考-您应该能够首先在
标记
字段上执行$unwind
,然后在同一个键上执行$group
,然后执行{$sum:1}
以获得计数。@chridam啊,当然,谢谢!