【问题标题】:Search within list of objects in mongodb using morphia使用morphia在mongodb中的对象列表中搜索
【发布时间】:2014-01-24 01:21:36
【问题描述】:

我对 Java 很陌生。我对 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,我什至不确定这是否是解决此问题的最佳方法。

【问题讨论】:

  • 你试过ds.createQuery(Clients.class).field("products.fooType").hasThisElement("bar")吗?
  • 同样的错误:invalid parameter: expected an object ($elemMatch)

标签: java mongodb morphia


【解决方案1】:

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);

【讨论】:

  • 我最初将其标记为正确,但我现在不确定。我希望能够通过 fooType 进行搜索。这似乎我需要与我正在寻找的对象完全匹配,而不是找到所有具有 fooType="bar" 的对象,对吗?
  • 你不需要使用 $elemMatch 操作符,除非你想匹配一个数组元素中的多个组件。
  • 这个查询 ds.createQuery(Clients.class).field("products").hasThisElement(filterProduct) 将被解释为: { "products" : { "$elemMatch" : { "fooType" : “酒吧”}}}。如果只想返回字段 products 中所有包含 "fooType":"bar" 的文档,可以使用查询 db.Clients.find({"products.fooType":"bar"}),对应的morphia 中的代码是:ds.createQuery(Clients.class).filter("products.fooType","bar");
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
相关资源
最近更新 更多