Dimka
Dimka

Reputation: 67

Aggregation query error 15982: "exception: field path references must be prefixed with a '$'"

Need help in creation aggregation query. At this time i have next code:

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);
}

But after run console said:

> 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 }

For this I used mongo aggreagtion query as below :

 db.students.aggregate([ 
                       { $match: { "scores.type": "homework" }},
                       {'$unwind' : '$scores' }, 
                       { $match : {"scores.type" : "homework"}},
                       {$sort : {_id:1, "scores.score":1}}
                     ])

What I'm doing wrong?

Upvotes: 2

Views: 2821

Answers (1)

Dimka
Dimka

Reputation: 67

Thx yogesh! The answer is

DBObject unwind = new BasicDBObject("$unwind", "$scores");

Upvotes: 1

Related Questions