mongodb 批量更新内嵌数组里面的内容
Criteria criteria = Criteria.where("comments.is_read").is(2).and("_id").is(new ObjectId("5cf642b95843667a86c8a6b5"));
Aggregation cAggregation = Aggregation.newAggregation(
Aggregation.unwind("comments"),
Aggregation.match(criteria), //查询条件
Aggregation.project("comments") //查询的字段
);
AggregationResults<BasicDBObject> cOutputTypeCount =
mongoTemplate.aggregate(cAggregation, "t_table_name", BasicDBObject.class);
Update update = new Update();
int i =0;
DBObject obj = null;
DBObject comments = null;
for (Iterator<BasicDBObject> iterator = cOutputTypeCount.iterator(); iterator.hasNext(); ) {
obj = iterator.next();
comments = (DBObject)obj.get("comments");
System.out.println(comments.get("is_read"));
update.set("comments."+i+".is_read", 3);
i = i+1;
System.out.println(JSON.toJSONString(comments));
}
Query query = new Query();
query.addCriteria(criteria);
mongoTemplate.updateMulti(query, update, TableName.class);
sql 命令:
db.t_neighbourhood.aggregate([{ "$unwind" : "$comments"} ,{ "$match" : { "comments.is_read" : 0 }} , { "$project" : { "comments" : 1}}])