0

我的 mongodb 客户集合具有以下字段:

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

我想运行 2 个查询,这些查询在 SQL 中如下所示:

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

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

另外,我mongoTemplate在 java 中使用,所以如果您可以使用mongoTemplate.

4

1 回答 1

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

于 2017-04-21T14:05:29.423 回答