如何使用MongoDB加入多个集合?

时间:2019-08-11 05:11:34

标签: java mongodb netbeans

我想加入集合部门报价,但是它不起作用,我也不知道问题出在哪里。

Java来源:

private void getRecordFromDeptYear(String selectedDept, String selectedYear) {
    DBObject match = new BasicDBObject("$match", new BasicDBObject("DeptID", selectedDept));

    // build the $lookup operations
    DBObject lookupFields = new BasicDBObject("from", "offer");
    lookupFields.put("localField", "DeptID");
    lookupFields.put("foreignField", "DeptID");
    lookupFields.put("as", "offer_department");
    DBObject lookup = new BasicDBObject("$lookup", lookupFields);

    DBObject projectFields = new BasicDBObject("DeptName", "$department.DeptName");
    projectFields.put("ClassSize", "$offer.ClassSize");
    DBObject project = new BasicDBObject("$project", projectFields);
    List<DBObject> pipeline = Arrays.asList(match, lookup, project);
    AggregationOutput output = collection.aggregate(pipeline);

    for (DBObject result : output.results()) {
        System.out.println(result);
    }
}

MongoDB代码:

db.getCollection('department').aggregate([
  { $match: { DeptID: "CS" } },
  { $lookup: { from: 'offer', localField: 'DeptID', foreignField: 'DeptID', as: 'department_offer' } }
])

例外:

Exception in thread "AWT-EventQueue-0"
com.mongodb.MongoCommandException: 
Command failed with error 9:
'The 'cursor' option is required, except for aggregate with the explain argument' on server localhost:27017.
The full response is
{ "ok" : 0.0, "errmsg" : "The 'cursor' option is required, except for aggregate with the explain argument", "code" : 9, "codeName" : "FailedToParse" }

0 个答案:

没有答案