count 计数

db.collection.count({"target_field": "a"});
db.collection.find({"target_field": "a"}).length();

#联合条件查询
db.users.count({
  $and: [
   {target_field1: 'a'},
   {target_field2: {$gte: 10}}
  ]
});

aggregate 数据统计

[1] - 统计特定字段target_field的数量和总数:

db.collection.aggregate([
  {$group:{_id:"$target_field",count:{$sum:1},total:{$sum:"$num"}}
]);

[2] - 统计status=1的target_field的数量:

db.collection.aggregate([
  {$match:{status:1}},
  {$group:{_id:"$target_field",count:{$sum:1}}}
]);

[3] - 统计target_field的数量,并且数量为小于2的数据:

db.collection.aggregate([
  {$group:{_id:"$target_field",count:{$sum:1}},
  {$match:{count:{$lt:2}}}
]);

[4] - 统计stauts=1的target_field的数量,并且数量为1的数据:

db.collection.aggregate([
  {$match:{status:1}},
  {$group:{_id:"$target_field",count:{$sum:1}}},
  {$match:{count:1}}
]);
Last modification:July 21st, 2022 at 02:13 pm