目录
- 找出数组中, 具有 qid=1并且reorderFlag=0的记录
- 找出数组中, qid=1 或者 reorderFlag=0的记录
- 新增数组数据
- 修改数组数据,根据条件批量修改嵌套数组的字段值
- 删除数组数据,根据条件删除数组对象
- 聚合(Aggregation.group),动态组装group聚合字段
- 聚合(Aggregation.group),统计字段类型出现的次数。
- 聚合(Aggregation.project),将数据字段转换成需要的Class字段输出
- 聚合(Aggregation.project),计算数组的长度
找出数组中, 具有 qid=1并且reorderFlag=0的记录
- mongod
{ "qList": { $elemMatch: { "qid": 1, "reorderFlag": 0} } }
找出数组中, qid=1 或者 reorderFlag=0的记录
- mongod
{ "qList.qid": 1, "qList.reorderFlag": 0}
新增数组数据
- java
update.push("teacher." + indexCode, JSON);
修改数组数据,根据条件批量修改嵌套数组的字段值
- mongod
db.teacher_index.update({level:1}, {$set:{"fields.$[].canEdit":1, "fields.$[].canSync":0}}, {multi:true, upsert:true})
- java
afterValueJSON.keySet().forEach(fieldCode -> {
update.set("teacher." + indexCode + ".$." + fieldCode, afterValueJSON.get(fieldCode));
});
删除数组数据,根据条件删除数组对象
- java
import com.mongodb.BasicDBObject;
update.pull("teacher." + indexCode, new BasicDBObject(TeacherDevelopConstant.ARRAY_DATA_ID, dataId));
聚合(Aggregation.group),动态组装group聚合字段
- java
GroupOperation group = Aggregation.group("code")
.first("code").as(TeacherDevelopConstant.TEACHER_DATA_CODE)
.first(TeacherDevelopConstant.CARD_ID).as(TeacherDevelopConstant.CARD_ID)
.first(TeacherDevelopConstant.UNIT_NAME).as(TeacherDevelopConstant.UNIT_NAME)
.first(TeacherDevelopConstant.USER_NAME).as(TeacherDevelopConstant.USER_NAME);
for (String indexName : unwindIndexMap.keySet()) {
group = group.push(indexName + ".dataId").as(indexName);
}
聚合(Aggregation.group),统计字段类型出现的次数。
类似于MySQL的SUM(IF(status = '男', 1, 0))
- java
Aggregation.group("code")
.sum(ConditionalOperators.when(Criteria.where("status").is(1)).then(1).otherwise(0)).as("processedNum")
聚合(Aggregation.project),将数据字段转换成需要的Class字段输出
- java
Aggregation.project(
Fields.from(
Fields.field("indexName", "indexNames"),
Fields.field("approvers"),
Fields.field("title"),
Fields.field("ruleCode", "code")
)
);
聚合(Aggregation.project),计算数组的长度
- mongod
[{
$project: {
"teacherDataCode": 1,
"userName": 1,
"teacher.zfsbspasp": {
$size: {
$ifNull: ['$report.teacher_zfsbspasp', []]
}
},
"teacher.jsdzfsb": {
$size: {
$ifNull: ['$teacher_jsdzfsb', []]
}
},
}
}]
- java
ProjectionOperation project = Aggregation.project("teacherDataCode", "unitCode", "unitName", "userName");
for (StatsIndexConfig index : qo.getConfigList()) {
project = project.andExpression("{$size: {$ifNull: {'$report.indexNamed', {}}}}", "[]").as("report."+index.getIndexName());
}
这个需要注意:project.andExpression方法需要把[]替换成{}