如何按客户ID选择所有客户组?

时间:2017-04-21 13:48:15

标签: mongodb mongodb-query aggregation-framework mongotemplate

我的mongodb客户系列包含以下字段:

{
    "_id" : ObjectId("582577eebac0ef176a8d0697"),
    "customerID" : NumberLong(37620089),
    "storeID" : NumberLong(1),
    "updatedDate" : ISODate("2017-03-27T14:07:11.278Z"),
    "customerName" : "hsingla cust"
}

我想在SQL中运行2个查询:

Select * from Customer group by customerID having storeID=1;
Select count(*) from Customer group by customerID having storeID=1;

我是mongodb的新手,我阅读过各种文章,但似乎无法得到正确答案。

此外,我在java中使用mongoTemplate,因此如果您可以使用mongoTemplate向我提供一些查询,将会有所帮助。

1 个答案:

答案 0 :(得分:0)

您可以将它们包装成一个聚合查询。

push("$$ROOT")作为customers作为查询的第一部分,count()作为第二部分的计数。

  TypedAggregation<Customers> agg = Aggregation.newAggregation(Customers.class,
            Aggregation.match(Criteria.where("storeID").is(1L)),
            Aggregation.group("customerID").
                    push("$$ROOT").as("customers").count().as("count"),
            Aggregation.unwind("customers"),
            Aggregation.sort(Sort.Direction.DESC, "customers.updatedData"),
            Aggregation.skip(5L),
            Aggregation.limit(10));
   List<Customers> results = mongoTemplate.aggregate(agg, "customer", Customers.class).getMappedResults();

此处更多$$ROOT - https://docs.mongodb.com/manual/reference/aggregation-variables/#system-variables