例外:在 mongo Java 中,FieldPath 'C6' 不以 $" 开头



我正在使用Java处理Mongodb。在某些条件下,我试图选择某些记录,包括group by。我使用的代码如下。

DBObject wherequery = new BasciDBOBject();
wherequery.put("deviceID", C6);
wherequery.put("reqTime", new BasicDBObject(
    "$lt", sometime)
    .append("$gt", someothertime));
DBObject project = new BasicDBObject("$project",
    wherequery);
DBObject groupFields = new BasicDBObject("_id",
    "$requestID");
DBObject group = new BasicDBObject("$group", groupFields);
AggregationOutput output = collection.aggregate(project, group);

当我运行此代码时,我得到以下错误:

exception: FieldPath 'C6' doesn't start with $"

这个错误意味着什么?它表示我使用过的deviceID C6。我错过了什么,或者我怎么错了?

请帮我解决

如果要选择符合指定条件的文档,则应在第一个管线阶段使用$match运算符,而不是$project运算符。

将您的wherequery添加到$match,对于project使用不同的DBObject检查代码,如下所示:

DBObject wherequery = new BasciDBOBject();
wherequery.put("deviceID",C6 );
wherequery.put("reqTime", new BasicDBObject(
    "$lt", sometime)
    .append("$gt", someothertime));
DBObject match = new BasicDBObject("$match",
    wherequery);
DBObject groupFields = new BasicDBObject("_id",
    "$requestID");
DBObject group = new BasicDBObject("$group", groupFields);
//for projecting data 
DBObject projectData = new BasciDBOBject();
projectData.put("deviceID", "$deviceID"); // projectData.put("deviceID", 1); this also work
projectData.put("reqTime", "$reqTime");
DBObject project = new BasicDBObject("$project",
    projectData);
AggregationOutput output = collection.aggregate(match, group,project);

有关更多信息,请查看此用于聚合的MongoJava驱动程序

相关内容

  • 没有找到相关文章

最新更新