mydb
mydb

Reputation: 45

MongoDB different result of aggregation

I have this query:

db.collection.aggregate([
  {
    $group: {
      _id: "$PATIENT_ID", 
      MASS: { $max: "$max_field" }
    }
  }
]); 

The result of this query is:

{ "_id" : "TCGA-A2-A0YD", "mass" : 0.994683301742671 }
{ "_id" : "TCGA-A2-A3XX", "mass" : 0.993455527786917 }

I have this second query:

db.collection.aggregate([
  {
    $group: {
      _id: "TCGA-A2-A3XX",
      MASS: { $max: "$max_field" }
    }
  }
]);

The result of this second query is:

{ "_id" : "TCGA-A2-A3XX", "mass" : 0.994683301742671 }

Why? I expected another value for this id TCGA-A2-A3XX

Upvotes: 3

Views: 164

Answers (1)

DAXaholic
DAXaholic

Reputation: 35408

Your problem is that you are grouping all documents by the constant "TCGA-A2-A3XX" and therefore you get a single group with that ID and calculate the maximum of the field from all documents.
I guess you want to add a $match stage to your pipeline to filter for your specific patient.

db.collection.aggregate([
  { 
    $match: {
      PATIENT_ID: "TCGA-A2-A3XX"
    }
  },
  {
    $group: {
      _id: "$PATIENT_ID",
      MASS: { $max: "$max_field" }
    }
  }
]);

Upvotes: 3

Related Questions