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}
]
你能帮我这个忙吗.....
答案 0 :(得分:1)
您需要$sort
items
数组以使其类似于其他items
数组,然后可以$group
与items
>
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 }}
])