MongoDB-集合集合上的聚合

时间:2018-10-02 07:48:39

标签: mongodb aggregate

我有一个看起来像这样的收藏集:

@Document(collection = "Contact")
public @Data class Contact {

    @Id
    private String id;
    private String institution;
    private List<ContactAddressWithProducts> addressesWithProducts;

,然后我将列出所有具有多个 addressesWithProducts 的联系人,包括addressesWithProducts.length的数量。

这是我的第一次尝试,但不起作用:

db.Contact.aggregate([{$group: { _id: {institution: "$institution"}, count: {$sum: {addressesWithProducts}} }}, {$match: {count: {"$gt": 1} }} ]);

有人知道如何解决吗?

[编辑] 集合如下所示:

{
"_id" : ObjectId("5a12c677c2dc334f8983a045"),
"_class" : "com.my.domain.dao.domain.Contact",
"institution" : "Contact name",
...
"addressesWithProducts" : [
    {
    "products" : [...]  
    "address" : DBRef("Address", ObjectId("59ede65fc2dc768853cc7843"))
    },
    {
    "products" : [...]  
    "address" : DBRef("Address", ObjectId("59ede6522222768853cc7843"))
    }
],


"creationDate" : ISODate("2017-11-20T12:11:00Z"),
"active" : true,
"address" : DBRef("Address", ObjectId("5a12c677c2dc334f8983a044")),
"tenant" : DBRef("Tenant", ObjectId("58500aed747a6cddb55ba094"))
}

我的预期输出应如下所示:

{ "_id" : { "institution" : "Contact name" }, "count" : 2 }
{ "_id" : { "institution" : "Contact name 123" }, "count" : 7 }
{ "_id" : { "institution" : "Contact name 5" }, "count" : 4 }
...

1 个答案:

答案 0 :(得分:1)

将查询更改为以下内容:

db['Contact'].aggregate(
    [
        {
            $group: {
            _id: {institution: "$institution"},
            count:{$sum:{$size:{ $ifNull: [ "$addressesWithProducts", [] ] }}}
            }
        },
        {
            $match: {
            count: {"$gt": 1}
            }
        },
    ]
);