我用Java编写了这个MongoDB查询:
DBObject group1 = new BasicDBObject();
group1.put("_id", new BasicDBObject("invoiceNo", "$invoiceNo")
.append("invoiceDate", "$invoiceDate")
.append("count", new BasicDBObject("$sum",1)));
DBObject group2 = new BasicDBObject();
group2.put("_id", new BasicDBObject("invoiceNo", "$_id.invoiceNo")
.append("count", new BasicDBObject("$sum",1)));
AggregationOutput output = dummyColl.aggregate(new BasicDBObject("$group", group1),
new BasicDBObject("$group", group2));
,代码是
com.mongodb.CommandFailureException: { "serverUsed" : "localhost/127.0.0.1:27017" , "errmsg" : "exception: invalid operator '$sum'" , "code" : 15999 , "ok" : 0.0}
at com.mongodb.CommandResult.getException(CommandResult.java:71)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:110)
at com.mongodb.DBCollection.aggregate(DBCollection.java:1308)
它给出错误
SELECT dfl.mydate, dfl.firststart, dfl.lastend, fa.ActivityA, sa.ActivityB
FROM
(select s.mydate, firststart, lastend FROM
(SELECT mydate, MIN(starttime) as firststart from target GROUP by mydate) s
iNNER JOIN
(SELECT mydate, MAX(EndTime) as lastend from target GROUP by mydate) e
ON s.mydate = e.mydate) AS dfl
INNER JOIN
target fa on dfl.mydate = fa.mydate and dfl.firststart = fa.starttime
INNER JOIN
target sa on dfl.mydate = sa.mydate and dfl.lastend = sa.EndTime
请帮我弄清楚错误。
答案 0 :(得分:1)
在您的代码中
group1.put("_id", new BasicDBObject("invoiceNo", "$invoiceNo")
.append("invoiceDate", "$invoiceDate")
.append("count", new BasicDBObject("$sum",1)));
类似于
$group: {
"_id":
{
"invoiceNo": "$invoiceNo",
"invoiceDate": "$invoiceDate",
"count": { "$sum", 1 }
}
}
但你需要的是
$group: {
"_id": { "invoiceNo": "$invoiceNo", "invoiceDate": "$invoiceDate" },
"count": { "$sum", 1 }
}
所以第一个查询将是
group1.put("_id", new BasicDBObject("invoiceNo", "$invoiceNo")
.append("invoiceDate", "$invoiceDate");
group1.put("count", new BasicDBObject("$sum", 1));
而第二个
group2.put("_id", new BasicDBObject("invoiceNo", "$_id.invoiceNo"));
group2.put("count", new BasicDBObject("$sum", 1));