MongoDB group of study notes (group) use example

  • 2020-05-17 06:51:37
  • OfStack


//  Prepare test data 
db.user.drop();
for(var i=10; i< 100; i++) {
  db.user.insert({
    name:"user" + i, 
    age : Math.floor(Math.random()*10)+ 20, 
    sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F',
    chinese : Math.floor(Math.random()*50)+50,
    math : Math.floor(Math.random()*50)+50,
    english : Math.floor(Math.random()*50)+50,
    class : "C" + i%5
  })
}

// group function 
//  In accordance with the class Group and display each class User name and gender 
db.user.group({
  key: {"class": true},
  initial: {"person": []},
  reduce: function(cur, prev) {
    prev.person.push({name: cur.name, sex: cur.sex, age: cur.age});
  }
});

//  right age>25 User, according to class Group and display each class The user name and gender of each group 
db.user.group({
  key: {"class": true},
  initial: {"person": []},
  reduce: function(doc, out){
    out.person.push({name: doc.name, sex: doc.sex, age: doc.age});
  },
  finalize: function(out){
    out.count = out.person.length;
  },
  condition: {"age": {$gt: 25}}
})

//  Group each class , chinese Maximum and minimum 
db.user.group({
  key: {"class": true},
  initial: {"chinese_min": 0, "chinese_max":0 },
  reduce: function(doc, out){
    out.chinese_min = doc.chinese;
    out.chinese_min = doc.chinese;

    out.chinese_min = Math.min(out.chinese_min, doc.chinese);
    out.chinese_max = Math.max(out.chinese_max, doc.chinese)
  },
})

//  By grouping, each total score and average score were calculated 
db.user.group({
  key: {"_id" : true},
  initial: {name:"", total: 0, avg: 0},
  reduce: function(doc, out){
    out.name = doc.name;
    out.total = doc.chinese + doc.math + doc.english;
    out.avg = Math.floor(out.total / 3);
  }
})

group parameter options:

1.key: this is key for grouping
2.initial: each group shares 1 initialization function. Special note: it is initial for each group.
3.reduce: the first parameter of this function is the current document object, and the second parameter is the accumulated object of the last function operation. $reduce is called as many times as there are documents.
4.condition: this is the filter condition.
5.finalize: this is a function that will trigger this method after each group of documents is executed.


Related articles: