目录
1、查询数组元组 比如 每条记录都有 score:[23,45,20],想查询score 所有分数都大于多少分数,或者含有等于多少分的
@Test
public void testFind3(){
final BasicDBObject test = new BasicDBObject("score", new BasicDBObject("$elemMatch", new BasicDBObject("$gt", 90).append("$lt", 100)));
final BasicDBObject keys = new BasicDBObject("score", 1);
DBCursor cursor = getCollection().find(test, keys);
while (cursor.hasNext()) {
DBObject object = cursor.next();
System.out.println(object);
}
cursor.close();
}
public void testFind3() {
Criteria cri = Criteria.where("$gt").is(90).and("$lt").is(100);
Query query = new Query(Criteria.where("score").elemMatch(cri));
query.fields().include("score");
List<Users> users = mongoTemplate.find(query, Users.class);
for(Users users2 : users) {
System.out.println(users2.toString());
}
}
criteria.and("score").elemMatch(new Criteria("$eq").is(26));
结果:
-
Users [id=5450e79182ce1953fb0adbd5, username=null, password=null, age=null, score=[88, 99, 100]]
-
Users [id=5450e7ae82ce1953fb0adbd6, username=null, password=null, age=null, score=[88, 99]]
-
Users [id=5450eaf982ce1953fb0adbd8, username=null, password=null, age=null, score=[88, 99]]
嵌套元素查询 json格式
有些字段如下
"historyList" : [
{
"_id" : "1",
"hh" : "1"
},
{
"_id" : "2",
"hh" : "2"
},
{
"_id" : "3",
"hh" : "2"
}
]
//正常的mongoTemplate写法
Query query = new Query();
query.addCriteria(Criteria.where("userId").is("2").and("historyList._id").is("1"));
System.out.println(query.toString());
return mongoTemplate.find(query,UseHistory.class);
//但是这种写法不能满足,会将符合查询要求的整行数据全部返回,包含所有的子集。
Aggregation写法
History history = null;
//封装对象列表查询条件
List<AggregationOperation> commonOperations = new ArrayList<>();
//1. 指定查询主文档
MatchOperation match = Aggregation.match(Criteria.where("userId").is("2"));
commonOperations.add(match);
//2. 指定投影,返回哪些字段
ProjectionOperation project = Aggregation.project("historyList");
commonOperations.add(project);
//3. 拆分内嵌文档
UnwindOperation unwind = Aggregation.unwind("historyList");
commonOperations.add(unwind);
//4. 指定查询子文档
MatchOperation match2 = Aggregation.match(
Criteria.where("historyList.hh").is("2"));
commonOperations.add(match2);
//创建管道查询对象
Aggregation aggregation = Aggregation.newAggregation(commonOperations);
AggregationResults<JSONObject> reminds = mongoTemplate
.aggregate(aggregation, "history", JSONObject.class);
List<JSONObject> mappedResults = reminds.getMappedResults();
if (mappedResults != null && mappedResults.size() > 0) {
history = JSONObject
.parseObject(mappedResults.get(0).getJSONObject("historyList").toJSONString(), History.class);
}
对数组元素进行追加,删除
//纯数组删除其中元素
{
"_id" : ObjectId("5b921e02d833f81e08fb674f"),
……
"code" : [
"6380500517",
"6380500518",
"6380500519"
]
}
db.表明.find(
{'code':'6380500517'}
)
db.表名.updateMany(
{'code':'6380500517'},
{'$pull': {'code':'6380500517'}}
)
//json格式数组删除其中一个元素
{
"_id" : ObjectId("56e2a92ccc6dd2271953e502"),
"links": [
{
"name": "Google",
"url": "http://www.google.com"
},
{
"name": "Baidu",
"url": "http://www.baidu.com"
},
{
"name": "SoSo",
"url": "http://www.SoSo.com"
}
]
}
//删除百度
db.collection.update(
{ _id: ObjectId('id') },
{ $pull: { links: { name: 'Baidu' } } }
);
...
criteria.and("id").is('xxx');//先定位到这一条
mongoQuery = new Query(criteria)
Update update = new Update();
update.pull("links",new BasicDBObject("name",'Baidu'));//从links中拉出符合条件的一条
mongoTemplate.updateMulti(mongoQuery, update, xx.class);
//数组追加
db.getCollection("DemoCollection").update({ "drId" :new NumberLong(" 4909159988835622912")} , { $push : { "contexts" : { "time" :new Date("2020-11-29 04:33:38.000"), "speaker" :new NumberLong( "4891554746090405888"), "context" : "MongoTemplate 并列条件查询和数组字段追加操作", "_class" : "xxx.xxx.xxx.pojo.po.Context"}}})
Context msg = new Context();
msg.setSpeaker(baseUserInfo.getUserId());
msg.setTime(new Date());
msg.setContext(context);
Query query = new Query();
query.addCriteria(Criteria.where("drId").is(dialogRecordId));
Update update = new Update();
update.push("contexts", msg);
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "DemoCollection");
if (updateResult.getMatchedCount() == 1) {
if (updateResult.getModifiedCount() >= 1) {
return "追加完成";
}
}
数组元素修改其中的一个jons值
{
"_id": ObjectId("5550622dfc194b340a1feb5f"),
"name": "hsaflkjhdf",
"desc": "dfsafsdafsafad",
"type": "微企模板",
"template": [
{
"_id": ObjectId("5550d3280a706d025d8eb5d6"),
"view": "aaaaaaaaaaa",
"image": "http://127.0.0.1:7012/staticdata/newsdata/template/images/redare/5550622dfc194b340a1feb5f/143136029221214278739681.jpg"
}
]
删除template子元素中的一条记录:
Update update = new Update();
update.pull("template",new BasicDBObject("id",templateId));
Query query = Query.query(Criteria.where("id").is(viewTemplateId));
return mongodbTemplate.updateFirst(query,update,ViewTemplate.class);
修改template子元素的某一条满足条件的记录:
Query query = Query.query(new Criteria().andOperator(Criteria.where("companyName").is(riskvo.getCompanyName()),Criteria.where("risks").elemMatch(Criteria.where("riskPoint").is(riskvo.getRiskPoint()))));
Update update = new Update();
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("riskPoint", riskvo.getRiskPoint());
// jsonObject.put("source", 1);
// jsonObject.put("riskDetail", riskvo.getRiskDetail());
// jsonObject.put("type", riskvo.getType());
update.set("risks.$.riskPoint", riskvo.getRiskPoint());
update.set("risks.$.riskDetail", riskvo.getRiskDetail());
update.set("risks.$.type", riskvo.getType());
update.set("risks.$.source", 1);
mongoTemplate.updateMulti(query, update, "machineAllocation");
数组元素去重追加一个或者多个值 $addToSet
添加值到一个数组中,如果该数组中已经存在该值,则不会添加;如果不存在该值,则添加
db.collcetion.update({"_id":"123"}, {"$addToSet":{"likes":"PingPang"}})
如果想要批量添加list,需要配合$each使用
db.collcetion.update({"_id":"123"}, {"$addToSet":{"likes":{"$each":["PingPang","FootBall","BasketBall"]}}})
//去重添加一个值
Query query = new Query(Criteria.where("_id").is(123))
Document updateDoc = new Document();
updateDoc.append("$addToSet", new Document().append("listKey", gameId));
BasicUpdate update = new BasicUpdate(updateDoc);
// 实现数据存在就更新,不存在就插入数据
mongoTemplate.upsert(query, update, docName);
//去重添加多个值
/**
* 批量更新用户信息组信息
* @param userIds
* @param groupIDs
*/
public void batchUpdateUser(Object[] userIds,Object[] groupIDs) {
Criteria c = Criteria.where("_id").in(userIds);
Update update = new Update();
Update.AddToSetBuilder ab = update.new AddToSetBuilder("groupIDs");
update = ab.each(groupIDs);
mongoTemplate.updateMulti(new Query(c),update,SystemContent.COLLECTION_NAME_APPLYUSER);
}