db.getCollection('collectionName').aggregate(
{ $match : { "labels.site_name" : "川A12345","start":{$gte : ISODate("2018-01-30T16:00:00.000Z"), $lte : ISODate("2018-12-31T16:00:00.000Z")}}},
{ $group : { _id : "$start", number :{ $sum : 1 }}},
{ $sort : { _id : -1 }}
使用aggregate方法;
$match是查询的方法;
$group 分组字段相关;
$sort 排序。
匹配一个Document中的字段是数组属性其中的值:$elemMatch
比如有如下记录:
{_id: ObjectId("53d760721423030c7e14267d"),
name: 'Tony',
categories: [
name: 'coder',
name: 'dotaer',
name: 'cook',
现在我想要匹配:name:tony和categories数组中name:dotaer的记录
语句如下:
find({"name":"Tony", "categories":{$elemMatch:{"name":"dotaer"})
匹配记录中有个属性是字符串数组中其中一个字符串,有个属性如下
"tags" : [
"state",
"stat"
查询语句如下:
db.getCollection('va').find({tags:"stat"})
强烈建议不要定义一个非对象的属性,如字符串数组,可以定义一个对象数组,对象中只有一个属性,字符串
SpringDataMongoDB
MongoTemplate template = factory.getMongoTemplate(DATABASE_NAME);
Query query = query(where("name").is(name));
People people = template.findOne(query, People.class,"people");
update更新
Update update = Update.update("更新字段名", 内容);
template.updateFirst(query, update, entityClass, collectionName);
group分组
Criteria criteria = Criteria.where("start").gte(begin).ite(end).and("name").is(name);
MatchOperation match = Aggregation.match(criteria);
GroupOperation group = Aggregation.group("start").count().as("count");
// 注group key start会映射成_id,所以要利用project阶段映射回start
ProjectionOperation project = Aggregation.project("count").and("_id").as("start");
Aggregation aggregation = Aggregation.newAggregation(match,group,project);
AggregationResults<Map> aggregate = template.aggregate(aggregation, "表名", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
Criteria 是查询条件,构建对象MatchOperation ,ProjectionOperation ,Aggregation;template是查询的数据库。
SpringDataMongoDB grouop更加详细的内容:https://blog.csdn.net/fs1360472174/article/details/74081487