0

I am working on a query to find the subject title, subject type, and credit value of subject with highest credit value. This is the query I have come up with:

 db.Subject.aggregate([{$match:{"subject.credit":{$max:true}},
{$project:{"subject.subTitle":1, "subject.type":1, "subject.credit":1,  _id: 0}}
]).pretty()

This doesn't seem to net anything. and

db.Subject.aggregate([{$match:{"subject.credit":$max}},
$project:{"subject.subTitle":1, "subject.type":1, "subject.credit":1,  _id: 0}}
]).pretty()

This nets and error as shown below:

E QUERY    [js] ReferenceError: $max is not defined :
@(shell):1:32

Here is a part of the database that contains the highest credit value:

db.Subject.insert(
{ 
    "_id":ObjectId(),
    "subject":{ 
        "subCode":"CSCI321",
        "subTitle":"Final Year Project",
        "credit":6,
        "type":"Core",
        "assessments": [
                { "assessNum": 1,
                  "weight":30,
                  "assessType":"Presentation",
                  "description":"Prototype demonstration" },
                { "assignNum": 2,
                  "weight":70,
                  "assessType":"Implementation and Presentation",
                  "description":"Final product Presentation and assessment of product implementation by panel of project supervisors" }
            ]
  }
}
)

2 Answers2

1

A good strategy, if you don't have an index, is to collapse all documents and get one value:

const pipeline =  [
    {
        "$project" : {
            "subTitle" : "$subject.subTitle",
            "type" : "$subject.type",
            "credit" : "$subject.credit",
            "_id" : 0
        }
    },
    {
        "$sort" : {
            "credit" : -1
        }
    },
    {
        "$limit" : 1
    }
]
db.Subject.aggregate(pipeline)

Query

  • $project We want only a subset of fields
  • $sort to get the highest credit first.
  • $limit:1 to get only the highest.
Minsky
  • 2,277
  • 10
  • 19
0
db.Subject.find({},{"subject.subTitle":1, "subject.type":1, "subject.credit":1,"_id":0}).sort({"subject.credit":-1})

just use this

vicky
  • 415
  • 2
  • 10
  • I am only looking to list out the subject title, type and credit for the subjects with the highest credit value. After testing your query, it lists out the subjects with the highest credit value 1st but also lists out every other entry. – Frio_Penitencia Nov 18 '20 at 02:33
  • I am also only allowed to utilize aggregate. – Frio_Penitencia Nov 18 '20 at 02:39