代码之家  ›  专栏  ›  技术社区  ›  quma

MongoDB-集合数组上的聚合

  •  0
  • quma  · 技术社区  · 6 年前

    @Document(collection = "Contact")
    public @Data class Contact {
    
        @Id
        private String id;
        private String institution;
        private List<ContactAddressWithProducts> addressesWithProducts;
    

    我会列出所有有多个联系人的联系人 产品地址

    这是我第一次尝试,但没有成功:

    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 回复  |  直到 6 年前
        1
  •  1
  •   matthPen    6 年前

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