MongoDB基于Morphia ( 一)常用操作

转载自::https://blog.csdn.net/small_love/article/details/6628200

   

           简介
           这个有两个修改你的数据库的方法。你可以insert/save一个完整的实体,或者通过update操作。我们将在一下讨论。
        Updating(On the server)
             总之,当你通过Datesote调用update方法时就会向MongoDB服务器发送一个修改已存在数据的指令。
             
              
                   

       
       
       
       
  1. interface Datastore {
  2. /** updates all entities found with the operations*/
  3. UpdateResults update(Query query, UpdateOperations ops);
  4. /** updates all entities found with the operations; if nothing is found insert the update as an entity if “createIfMissing” is true*/
  5. UpdateResults update(Query query, UpdateOperations ops, boolean createIfMissing);
  6. /** updates the first entity found with the operations*/
  7. UpdateResults updateFirst(Query query, UpdateOperations ops);
  8. /** updates the first entity found with the operations; if nothing is found insert the update as an entity if “createIfMissing” is true*/
  9. UpdateResults updateFirst(Query query, UpdateOperations ops, boolean createIfMissing);
  10. /** updates the first entity found with the operations; if nothing is found insert the update as an entity if “createIfMissing” is true*/
  11. UpdateResults updateFirst(Query query, T entity, boolean createIfMissing);
  12. }
  13. public interface UpdateOperations<T> {
  14. /** sets the field value */
  15. UpdateOperations set(String fieldExpr, Object value);
  16. /** removes the field */
  17. UpdateOperations unset(String fieldExpr);
  18. /** adds the value to an array field*/
  19. UpdateOperations add(String fieldExpr, Object value);
  20. UpdateOperations add(String fieldExpr, Object value, boolean addDups);
  21. /** adds the values to an array field*/
  22. UpdateOperations addAll(String fieldExpr, List values, boolean addDups);
  23. /** removes the first value from the array*/
  24. UpdateOperations removeFirst(String fieldExpr);
  25. /** removes the last value from the array*/
  26. UpdateOperations removeLast(String fieldExpr);
  27. /** removes the value from the array field*/
  28. UpdateOperations removeAll(String fieldExpr, Object value);
  29. /** removes the values from the array field*/
  30. UpdateOperations removeAll(String fieldExpr, List values);
  31. /** decrements the numeric field by 1*/
  32. UpdateOperations dec(String fieldExpr);
  33. /** increments the numeric field by 1*/
  34. UpdateOperations inc(String fieldExpr);
  35. /** increments the numeric field by value (negatives are allowed)*/
  36. UpdateOperations inc(String fieldExpr, Number value);
  37. }

               
         The Field Expression
           属性表达式是用在所有的操作上的,可以是单个的属性名,也可以是用点“.”连接的嵌套属性。在表达式中你也可以使用位置操作副($)。在属性
          表达式中没有标准,你可以使用任何在MongoDB服务端有效符号。
         
         事例初始化
              一下所有的实例创建的连接和Morphia实例都使用的一下代码。
                    

      
      
      
      
  1. Morphia morphia = new Morphia();
  2. morphia.map(Hotel.class).map(Address.class);
  3. Datastore datastore = morphia.createDatastore( “MorphiaSampleDb”);
  4. Hotel hotel = new Hotel( “Fairmont”, 3, new Address( “1 Rideau Street”, “Ottawa”, “K1N8S7”, “Canada”));
  5. datastore.save(hotel);
  6. UpdateOperations ops;
  7. // This query will be used in the samples to restrict the update operations to only the hotel we just created.
  8. // If this was not supplied, by default the update() operates on all documents in the collection.
  9. // We could use any field here but _id will be unique and mongodb by default puts an index on the _id field so this should be fast!
  10. Query updateQuery = datastore.createQuery(Hotel.class).field( “_id”).equal(hotel.getId());
  11. // The Mapper class also provides a public static of the default _id field name for us…
  12. Query updateQuery = datastore.createQuery(Hotel.class).field(Mapper.ID_KEY).equal(hotel.getId());

         注意: 使用的是 equal() 而不是 equals()
              

      
      
      
      
  1. @Entity( “hotels”)
  2. public class Hotel
  3. {
  4.    @Id
  5.    private ObjectId id;
  6.    private String name;
  7.    private int stars;
  8.    @Embedded
  9.    private Address address;
  10.    @Embedded
  11.    List roomNumbers = new ArrayList();
  12.    // … getters and setters
  13. }
  14. @Embedded
  15. public class Address
  16. {
  17.    private String street;
  18.    private String city;
  19.    private String postalCode;
  20.    private String country;
  21.    // … getters and setters
  22. }
      
     set/unset
            

      
      
      
      
  1. // 改变Hotel的name属性值
  2. ops = datastore.createUpdateOperations(Hotel.class).set( “name”, “Fairmont Chateau Laurier”);
  3. datastore.update(updateQuery, ops);
  4. //也可以操作嵌套文档, 改变address的city属性值
ops = datastore.createUpdateOperations(Hotel.class).set("address.city", "Ottawa");
      
      
      
      

      
      
      
      
  1. datastore.update(updateQuery, ops);
  2. // 删除Hotel的name属性值
  3. // 当下会访问Hotel时name属性为null
  4. ops = datastore.createUpdateOperations(Hotel.class).unset( "name");
  5. datastore.update(updateQuery, ops);
   
       inc/dec
          

      
      
      
      
  1. // ‘stars’属性增长一
  2. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”);
  3. datastore.update(updateQuery, ops);
  4. // ‘stars’属性值增长4
  5. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, 4);
  6. datastore.update(updateQuery, ops);
  7. // ‘stars’属性值减少1
  8. ops = datastore.createUpdateOperations(Hotel.class).dec( “stars”); // 和 .inc(“stars”, -1) 相同
  9. datastore.update(updateQuery, ops);
  10. // ‘stars’属性值减少4
  11. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, - 4);
  12. datastore.update(updateQuery, ops);
    
      add/All
            

      
      
      
      
  1. // 把一个值放入到数组中 array() (+v 0.95)
  2. // same as .add(“roomNumbers”, 11, false)
  3. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 11);
  4. datastore.update(updateQuery, ops); // [ 11 ]
    当在一个不是数组的属性上进行数组操作时MongoDB将会抛出错误。
      

      
      
      
      
  1. ops = datastore.createUpdateOperations(Hotel.class).set( “roomNumbers”, 11);
  2. datastore.update(updateQuery, ops);
  3. // 由于没有rooNumbers数组将会引起错误
  4. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 11, false);
  5. datastore.update(updateQuery, ops); // causes error
  6. // 删除roomNummbers属性
  7. ops = datastore.createUpdateOperations(Hotel.class).unset( “roomNumbers”);
  8. datastore.update(updateQuery, ops);
  9. // use the 3rd parameter to add duplicates
  10. // add to end of array, same as add()
  11. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 11, false);
  12. datastore.update(updateQuery, ops); // [ 11 ]
  13. // no change since its a duplicate… doesn’t cause error
  14. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 11, false);
  15. datastore.update(updateQuery, ops); // [ 11 ]
  16. // push onto the end of the array
  17. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 12, false);
  18. datastore.update(updateQuery, ops); // [ 11, 12 ]
  19. // add even if its a duplicate
  20. ops = datastore.createUpdateOperations(Hotel.class).add( “roomNumbers”, 11, true);
  21. datastore.update(updateQuery, ops); // [ 11, 12, 11 ]

     removeFirst/Last/All

            

      
      
      
      
  1. //given roomNumbers = [ 1, 2, 3 ]
  2. ops = datastore.createUpdateOperations(Hotel.class).removeFirst( “roomNumbers”);
  3. datastore.update(updateQuery, ops); // [ 2, 3 ]
  4. //given roomNumbers = [ 1, 2, 3 ]
  5. ops = datastore.createUpdateOperations(Hotel.class).removeLast( “roomNumbers”);
  6. datastore.update(updateQuery, ops); // [ 1, 2 ]
  7. ops = datastore.createUpdateOperations(Hotel.class).removeLast( “roomNumbers”);
  8. datastore.update(updateQuery, ops); // [ 1 ]
  9. ops = datastore.createUpdateOperations(Hotel.class).removeLast( “roomNumbers”);
  10. datastore.update(updateQuery, ops); // [] empty array
  11. //given roomNumbers = [ 1, 2, 3, 3 ]
  12. ops = datastore.createUpdateOperations(Hotel.class).removeAll( “roomNumbers”, 3);
  13. datastore.update(updateQuery, ops); // [ 1, 2 ]
  14. //given roomNumbers = [ 1, 2, 3, 3 ]
  15. ops = datastore.createUpdateOperations(Hotel.class).removeAll( “roomNumbers”, Arrays.asList( 2, 3));
  16. datastore.update(updateQuery, ops); // [ 1 ]
    

   Multiple Operations

           你也可以在一个update指令中执行多个updae操作。
           

      
      
      
      
  1. //设置城市名称为Ottawa和是stars的增长1
  2. ops = datastore.createUpdateOperations(Hotel.class).set( “city”, “Ottawa”).inc( “stars”);
  3. datastore.update(updateQuery, ops);
  4. //如果你在同一个属性上执行多次同样的指令操作,结果将会变化,即:只有最后一次有效
  5. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, 50).inc( “stars”); //stars只增长1
  6. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”).inc( “stars”, 50); //stars只增长50
  7. //你不能在同一个属性上执行相矛盾的操作。
  8. ops = datastore.createUpdateOperations(Hotel.class).set( “stars”, 1).inc( “stars”, 50); //引起错误
       updateFirst方法            在默认的驱动和shell上这是默认的行为。在Morphia中我们认为修改所有的符合条件的结果是最好的默认选择(如下)。
              {name: “Fairmont”, stars: 5}, {name: “Last Chance”, stars: 3}
              

      
      
      
      
  1. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, 50);
  2. // (+v 0.95 now takes into account the order())
  3. // morphia 执行updateFirst方法仅仅执行第一个符合查询条件的数据项
  4. datastore.updateFirst(datastore.find(Hotel.class).order( “stars”), ops); //仅仅修改Last Chance
  5. datastore.updateFirst(datastore.find(Hotel.class).order( “-stars”), ops); // 仅仅修改 Fairmont

      
      
      
      
  1. //default shell version is to match first
  2. //shell version has a multi to indicate to update all matches, not just first
  3. //to mimic morphia operation, set multi = false
  4. db.collection.update( criteria, objNew, upsert, multi );

     update 方法
            

      
      
      
      
  1. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, 50);
  2. // morphia 默认的update是修改所有的Hotels
  3. datastore.update(datastore.createQuery(Hotel.class), ops); //所有的hotel都会增长

      
      
      
      
  1. //equivalent morphia shell version is... upsert = false, multi = true
  2. db.collection.update( criteria, objNew, false, true );
     createIfMissing (overload parameter)
        所有的update都被重载支持一个”createIfMissing”参数。
       

      
      
      
      
  1. ops = datastore.createUpdateOperations(Hotel.class).inc( “stars”, 50);
  2. //修改, 如果没有找到就添加一个。
  3. datastore.updateFirst(datastore.createQuery(Hotel.class).field( “stars”).greaterThan( 100), ops, true);
  4. // creates { “_id” : ObjectId(“4c60629d2f1200000000161d”), “stars” : 50 }
  5. //equivalent morphia shell version is… upsert = true
  6. db.collection.update( criteria, objNew, true, multi );
      英语水平有限,敬请大侠 斧正
    原文连接:http://code.google.com/p/morphia/wiki/Updating
            

你可能感兴趣的:(mongo)