【问题标题】:getting count based on array of element in mongoDB根据 mongoDB 中的元素数组获取计数
【发布时间】:2019-01-27 06:15:02
【问题描述】:

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

[
   {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}
]

你能帮我解决这个问题吗.....

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案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 }}
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多