在创建聚合查询中需要帮助。这时我有下一个代码:
MongoClient client = new MongoClient();
DB base = client.getDB("school");
DBCollection collection = base.getCollection("students");
DBObject match = new BasicDBObject("$match", new BasicDBObject("scores.type", "homework"));
DBObject unwind = new BasicDBObject("$unwind", "scores");
DBObject sortFields = new BasicDBObject("_id", 1);
sortFields.put("scores.score", -1);
DBObject sort = new BasicDBObject("$sort", sortFields);
List<DBObject> pipeline = Arrays.asList(match, unwind, match, sort);
AggregationOutput output = collection.aggregate(pipeline);
for (DBObject result : output.results()) {
System.out.println(result);
}
但运行后控制台说:
> Command failed with error 15982: 'exception: field path references
> must be prefixed with a '$' ('scores'' on server 127.0.0.1:27017. The full response is { "errmsg" : "exception: field path references must be prefixed with a '$' ('scores'", "code" : 15982, "ok" : 0.0 }
为此,我使用了mongo aggreagtion查询,如下所示:
db.students.aggregate([
{ $match: { "scores.type": "homework" }},
{'$unwind' : '$scores' },
{ $match : {"scores.type" : "homework"}},
{$sort : {_id:1, "scores.score":1}}
])
我做错了什么?
答案 0 :(得分:1)
Thx yogesh! 答案是
DBObject unwind = new BasicDBObject(“$ unwind”,“$ scores”);