2014-01-24 42 views
0

我對Java很新。我對mongoDB非常陌生。使用morphia在mongodb中的對象列表內搜索

我有一個集合,它看起來是這樣的:

{ 
    "_id" : "1234", 
    "name" : "bill", 
    "products" : [ 
     { 
      "fooType" : "bar", 
      ..... 
     }, 
     { 
      "fooType" : "oof", 
      ..... 
     }   
    ], 
    "status" : "Truncated" 
}, 
{...} 

我想實現一個搜索功能通過fooType進行搜索。我能夠使用標準mongodb語法創建工作查詢,但無法弄清楚如何使用morphia實現。

一個工作的MongoDB查詢:

db.Clients.find({products: {$elemMatch: {fooType: "bar"}}}) 

,我已經沒有任何成功嘗試了一些(截)代碼:

DatastoreImpl ds; 
q = ds.createQuery(Clients.class).field("products").hasThisElement("fooType"); 

顯然,這並不工作,因爲它期望的對象。我似乎無法圍繞如何使用hasThisElement,我甚至不確定這是否是最好的方式去解決這個問題。

+0

你試過'ds.createQuery(Clients.class).field(「products.fooType」)。hasThisElement(「bar」)'? –

+0

同樣的錯誤:'無效參數:預計一個對象($ elemMatch)' –

回答

3

hasThisElement期望參數中有一個對象,所以你不能使用字符串「fooType」或「bar」。

假設您有以下類此集合:

class Clients { 
String id; 
String name; 
List<Product> products = new ArrayList<Product>(); 
String status; 
} 

class Product { 
String fooType; 
.... 
} 

要使用$elemMatch,你需要創建用於products如下過濾的對象,並在hasThisElement()使用此過濾器對象:

Product filterProduct = new Product(); 
filterProduct.fooType = "bar"; 
Query q = ds.createQuery(Clients.class).field("products").hasThisElement(filterProduct); 
+0

我最初標記爲正確的,但我現在還不確定。我希望能夠通過fooType進行搜索。這似乎是我需要與我正在查找的對象完全匹配,而不是找到所有具有fooType =「bar」的對象,是否正確? –

+0

除非要匹配數組元素中的多個組件,否則不需要使用$ elemMatch運算符。 –

+2

此查詢ds.createQuery(Clients.class).field(「products」)。hasThisElement(filterProduct)將被解釋爲:{「products」:{「$ elemMatch」:{「fooType」:「bar」}}} 。如果您只想返回所有在現場產品中具有「fooType」:「bar」的文檔,則可以使用查詢db.Clients.find({「products.fooType」:「bar」})和相應的morphia中的代碼是:ds.createQuery(Clients.class).filter(「products.fooType」,「bar」); –