Issue with mongosh (mongo shell) and $unwind

209 views Asked by At

We've used the following code (saved as example.js) in the past prior to mongosh.

// DB Connection
conn = new Mongo("localhost:27017");
db = conn.getDB("College2");
collSect = db.getCollection("Section");
collStudent = db.getCollection("Student");

// Create IDs
var secID1 = new ObjectId();
var secID2 = new ObjectId();
var stID1 = new ObjectId();
var stID2 = new ObjectId();
var stID3 = new ObjectId();

// Create Students
collStudent.insertOne({
            _id: stID1,
            uid: 123456789,
            firstName: "Ivona",
            lastName: "Bok",
            year: 3
        });

collStudent.insertOne({
            _id: stID2,
            uid: 234567890,
            firstName: "Ivan",
            lastName: "Smith",
            year: 4
        });

collStudent.insertOne({
            _id: stID3,
            uid: 345678901,
            firstName: "Sally",
            lastName: "Struthers",
            year: 4
        });

// insert sections with student references
collSect.insert({
    sectionID: "ISTE12301",
    title: "My Database Course",
    creditHours: 3,
    room: "GOL-2650",
    studentRefs: [
        {
            $ref: "Student", $id: stID1, $db: "College2"
        },
        {
            $ref: "Student", $id: stID2, $db: "College2"
        }
    ]
});

collSect.insert({
    sectionID: "ISTE23401",
    title: "My Other Database Course",
    creditHours: 4,
    room: "GOL-2620",
    studentRefs: [
        {
            $ref: "Student", $id: stID2, $db: "College2"
        },
        {
            $ref: "Student", $id: stID3, $db: "College2"
        }
    ]
});

// List Sections
print("\nQ2\n");
print("List Sections\n");
result = collSect.find();

while (result.hasNext()) {
    printjson(result.next());
}

// List Students
print("List Students\n");
result = collStudent.find();

while (result.hasNext()) {
    printjson(result.next());
}

// Use unwind and list results
print("List Sections with unwind\n");
result = collSect.find();

while (result.hasNext()) {
    printjson(result.next());
}

result = collSect.aggregate([{$unwind: "$studentRefs"}]);

// Print the section/student combination
while (result.hasNext()) {
    doc = result.next();
    studRef = doc.studentRefs;
    
    doc2 = db[studRef.$ref].findOne({_id: studRef.$id});
    print(doc.sectionID, doc2.firstName, doc2.lastName);
}

If I go into mongosh and issue load("example.js"), after unwinding when trying to build doc2 it gets null: TypeError: Cannot read property 'firstName' of null

However, if I am at the command prompt and issue mongo example.js, it works fine.

This seems odd since MongoDB is pushing users to mongosh. Does anyone know why this doesn't work in mongosh?

0

There are 0 answers