insert 如果主键("_id")在数据库中存在,则不做任何处理。
save如果主键("_id")在数据库中存在,则进行更新
insert和save方法的区别
insert 不校验数据是否存在,直接插入,如果重复的话,报错.
save 插入重复数据,则改用update
- /**
- * 使用save()方法保存数据
- * @param collection “表”名
- */
- private static void saveData(DBCollection collection){
- DBObject saveData=new BasicDBObject();
- saveData.put("userName", "iwtxokhtd");
- saveData.put("age", "26");
- saveData.put("gender", "m");
- DBObject infoData=new BasicDBObject();
- infoData.put("height", 16.3);
- infoData.put("weight", 22);
- saveData.put("info", infoData);
- collection.save(saveData);
- }
- /**
- * 使用insert()方法保存数据
- * @param collection "表"名
- */
- private static void insertData(DBCollection collection){
- DBObject insertData=new BasicDBObject();
- insertData.put("name", "pig");
- insertData.put("headers", 2);
- insertData.put("legs", 4);
- //insert(DBObject obj)
- collection.insert(insertData);
- DBObject insertDataFox=new BasicDBObject();
- insertDataFox.put("name", "fox");
- insertDataFox.put("headers", 1);
- insertDataFox.put("legs", 4);
- DBObject insertDataTiger=new BasicDBObject();
- insertDataTiger.put("name", "tiger");
- insertDataTiger.put("headers", 1);
- insertDataTiger.put("legs", 3);
- List<DBObject> insertDataList=new ArrayList<DBObject>();
- insertDataList.add(insertDataFox);
- insertDataList.add(insertDataTiger);
- //insert(List<DBObject> list)
- collection.insert(insertDataList);
- }