Saravanan S
Saravanan S

Reputation: 1043

Mongo query - finding minimum value within a document

I want to find minimum value in a mongoDB document:

Sample document

db.marks.insert({"name" : "John", "subject1" : 100, "subject2" : 98, "subject3" : 99, "subject4" : 97});

I want to find minimum value of subject1,subject2,subject3,subject4 inside each document. Tried to use aggregation framework for this, but it seems to work across documents. Is there a way to find value inside a document?

Upvotes: 1

Views: 1115

Answers (1)

BatScream
BatScream

Reputation: 19700

You could aggregate as below:

  • $group by the name to transform the subject fields to array.
  • $project a field named score as a $setUnion of all the scores per person.
  • $unwind the score array.
  • $group by the name again to find the $min score per person.

Code:

db.marks.aggregate([
{$group:{"_id":"$name",
         "subject1":{$push:"$subject1"},
         "subject2":{$push:"$subject2"},
         "subject3":{$push:"$subject3"},
         "subject4":{$push:"$subject4"}}},
{$project:{"score":{$setUnion:["$subject1",
                               "$subject2",
                               "$subject3",
                               "$subject4"]}}},
{$unwind:"$score"},
{$group:{"_id":"$_id","minScore":{$min:"$score"}}}
])

Upvotes: 1

Related Questions