2015-05-27 38 views
1

我對spring數據mongodb不熟悉,但我只是堅持,如何使用mongo存儲庫編寫基於json的嵌入式文檔查詢。如何編寫查詢更新嵌入式文檔

我的數據庫看起來像

"_id" : ObjectId("5565ad670cf25cbd975ab2d9"), 
    "_class" : "com.samepinch.domain.metadata.Metadata", 
    "preferenceType" : "shopping", 
    "subtypes" : [ 
     { 
      "_id" : ObjectId("5565ad670cf25cbd975ab2d2"), 
      "subType" : "veg", 
      "preferencePoint" : 0 
     }, 
     { 
      "_id" : null, 
      "subType" : "nonveg", 
      "preferencePoint" : 0 
     } 
    ], 
    "createdDate" : ISODate("2015-05-27T11:41:27.357Z"), 
    "updatedDate" : ISODate("2015-05-27T11:41:27.357Z") 

我想更新基於頂層文件ID,我必須更新preferencePoint具有ID 5565ad670cf25cbd975ab2d2 亞型亞型,如何編寫查詢呢?

回答

2

你應該使用$ projection$elemMatch查詢的樣子:

db.collectionName.update({"_id" : ObjectId("5565ad670cf25cbd975ab2d9"), 
"subtypes":{"$elemMatch":{"_id":ObjectId("5565ad670cf25cbd975ab2d2")}}}, 
{"$set":{"subtypes.$.preferencePoint":1}}) 

而其相應的Java代碼:

BasicDBObject eleMatch = new BasicDBObject(); 
eleMatch.put("_id", new ObjectId("5565ad670cf25cbd975ab2d2")); 
BasicDBObject elemMatchQuery = new BasicDBObject(); 
elemMatchQuery.put("$elemMatch", eleMatch); 
BasicDBObject query = new BasicDBObject(); 
query.put("_id", new ObjectId("5565ad670cf25cbd975ab2d9")); 
query.put("subtypes", elemMatchQuery); 
BasicDBObject set = new BasicDBObject(); 
set.put("subtypes.$.preferencePoint", 1); 
BasicDBObject update = new BasicDBObject(); 
update.put("$set", set); 
DBCollection dbcoll = mongoTemplate.getCollection("collectionName"); 
DBObject object = dbcoll.update(query, update); 
+0

感謝快速回復,但如何將其寫在像@查詢庫(),我完全新的春天MongoDB的數據,在此先感謝 –

+0

@PrabjotSingh我沒有太多的舒適性在春季倉庫裏面, [this](http://docs.spring.io/spring-data/mongodb/docs/1.2.x/reference/html/mongo.repositories.html)可能會有幫助 – Yogesh

+0

好吧,那很好,我會嘗試和感謝那一個答案 –

0

從@Query Java文檔org.springframework.data。 mongodb .repository。 查詢

註釋直接在倉庫 方法聲明取景查詢。這兩個屬性都允許使用佔位符符號?0,?1 等。

這裏你可以傳遞給註釋(下)

從看來你只能讀取,對特定領域的過濾器,執行數(),或刪除域對象定義的所有屬性,這些屬性匹配您的查詢。我沒有看到有關更新的任何信息。

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
@Documented 
@QueryAnnotation 
public @interface Query { 

    /** 
    * Takes a MongoDB JSON string to define the actual query to be executed. This one will take precendece over the 
    * method name then. 
    * 
    * @return 
    */ 
    String value() default ""; 

    /** 
    * Defines the fields that should be returned for the given query. Note that only these fields will make it into the 
    * domain object returned. 
    * 
    * @return 
    */ 
    String fields() default ""; 

    /** 
    * Returns whether the query defined should be executed as count projection. 
    * 
    * @since 1.3 
    * @return 
    */ 
    boolean count() default false; 

    /** 
    * Returns whether the query should delete matching documents. 
    * 
    * @since 1.5 
    * @return 
    */ 
    boolean delete() default false;