MongoDB中的数据
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"name": "张三",
"age": 15,
"arr": [1,2,3],
"arrObj":[{
"field1":"value1",
"field2":"value2"
}]
}
{
"_id": ObjectId("67c43caed4c63d7e39b5dc57"),
"name": "李四",
"age": 16,
"arr": [4,5,6]
}
DBCollection的获取
MongoTemplate template;
DBCollection collection = template.getDb().getCollection("colectionName");
1.根据ObjectId
BasicDBObject query = new BasicDBObject("_id", new ObjectId("67c43caed4c63d7e39b5dc57"));
collection.find(query);
2.in查询
ArrayList objectIds = new ArrayList<>();
objectIds.add(new ObjectId("67c43caed4c63d7e39b5dc57"));
objectIds.add(new ObjectId("67c43caed4c63d7e39b5dc58"));
QueryBuilder queryBuilder = QueryBuilder.start("_id").in(objectIds);
DBCursor dBCursor= collection.find(queryBuilder.get());
3.查询指定返回字段
BasicDBObject query = new BasicDBObject("_id", new ObjectId("67c43caed4c63d7e39b5dc57"));
BasicDBObject field = new BasicDBObject("name", true);
collection.find(query, field );
1.根据ObjectId删除
BasicDBObject query = new BasicDBObject("_id", new ObjectId("67c43caed4c63d7e39b5dc57"))
collection.remove(query );
1.整个文档更新
BasicDBObject dbObject = BasicDBObject.parse("{name:'王五'}");
dbObject.put("_id", new ObjectId("67c43caed4c63d7e39b5dc57"));
WriteResult writeResult = collection.save(dbObject);
2.更新数组中某一条数据
BasicDBObject query= BasicDBObject.parse("{name:'张三'}");
BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("arrObj.0.field1", "val1"));
WriteResult writeResult = collection.update(query, update);
// 执行查询返回dBCursor
DBCursor dBCursor= collection.find(query);
if(dBCursor.hasNext()){
DBObject next = dBCursor.next();
BasicDBObject basicDBObject = (BasicDBObject) next;
System.out.println(basicDBObject .toJson());
}