基于mongoDB中的元素数组进行计数

时间:2019-01-27 06:15:03

标签: mongodb mongodb-query aggregation-framework

im试图基于元素数组获取文档数。我的收藏有类似...的文件

[
   {pid: "p001", items :["apple","bat","cat"]},
   {pid: "p002", items :["apple","cat","bat"]},
   {pid: "p003", items :["apple","bat","cat","dog"]},
   {pid: "p004", items :["apple","bat","cat","dog"]}
]

我编写了一个mongo聚合查询,例如

db.collection_name.aggregate([
   {$group : {_id: "$items", count: {$sum : 1}}},
   {$project : { _id: 0, items: "$_id" , count: 1 } }
])

即时获得类似

的输出
[
   {items: ["apple","bat","cat"], count: 1},
   {items: ["apple","cat","bat"], count: 1},
   {items: ["apple","bat","cat","dog"], count: 2}
]

但是我想要我的输出

[
    {items: ["apple","bat","cat"], count: 2},
    {items: ["apple","bat","cat","dog"], count: 2}
]

你能帮我这个忙吗.....

1 个答案:

答案 0 :(得分:1)

您需要$sort items数组以使其类似于其他items数组,然后可以$groupitems

db.collection.aggregate([
  { "$unwind": "$items" },
  { "$sort": { "items": 1 }},
  { "$group": { "_id": "$pid", "items": { "$push": "$items" }}},
  { "$group": { "_id": "$items", "count": { "$sum": 1 }}},
  { "$project": { "_id": 0, "items": "$_id", "count": 1 }}
])