1.普通更新
sql
db.units.update({
"_id": ObjectId("605374c0966b648b2d99ef24")
}, {
$set: {
'userList': [
{
userId: "6054098870b571137b9d430f",
aliasNo: "F8N38P63",
aliasName: "F8N38P63",
_class: "com.otis.one.se.model.unit.UnitManager"
}
]
}
});
代码:
Query query = new Query(Criteria.where("_id").is(new ObjectId(id)));
Update update = new Update().set("userList", userList);
UpdateResult updateResult = mongo.updateFirst(query, update, COLLECTION_NAME);
2.更新某一字段的list $addToSet $each
db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
)
代码:
Query query = new Query(Criteria.where("_id").is(2));
Update update = new Update();
Update.AddToSetBuilder ab = update.new AddToSetBuilder("tags");
update = ab.each(tags);
UpdateResult updateResult = mongo.updateFirst(query, update, COLLECTION_NAME);
3.更新子属性list中的某一字段
代码
public long updateDeviceUser(UnitUserParam unitUserParam, String userId) {
Unit unit = getUnitByUnitIdStr(unitUserParam.getUnitId());
Update update = new Update();
update.set("userList.$.aliasNo", unitUserParam.getAliasNo());
update.set("userList.$.aliasName", unitUserParam.getAliasName());
Query updateQuery = new Query(
Criteria.where("unitNumber").is(unit.getUnitNumber()).and("userList.userId").is(userId));
UpdateResult updateResult = mongo.updateFirst(updateQuery, update, COLLECTION_NAME);
return updateResult.getModifiedCount();
}
|