Question

I am very new to Java. I am very new to mongoDB.

I have a collection that looks something like this:

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

I am trying to implement a search feature to search by fooType. I am able to create a working query using standard mongodb syntax, but cannot figure out how to implement using morphia.

A working mongodb query :

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

Some (truncated) code that I've tried without any success:

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

Obviously this doesn't work because it expects an object. I can't seem to wrap my head around how to use hasThisElement, and I'm not even sure if that's the best way to go about this anymore.

Was it helpful?

Solution

hasThisElement expects an object in the parameter, so you couldn't use a String "fooType" or “bar”.

Assume that you have the following classes for this collection:

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

class Product {
String fooType;
....
}

To use $elemMatch, you would need to create an object for the filter on products as below, and use this filter object in hasThisElement():

Product filterProduct = new Product();
filterProduct.fooType = "bar";
Query q = ds.createQuery(Clients.class).field("products").hasThisElement(filterProduct);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top