1

I want to get a list of unique values from a List field called categories.

I am using Java and MongoDB. Most of the examples and docs I can see seem to suggest I need to do something like what I have below:

public static List<String> listCategories(String input) {

    Datastore ds = Dao.instance().getDatabase();
    BasicDBObject dbObject=new BasicDBObject("categories", input);
    DBCollection dBCollection = ds.getCollection(Product.class);
    List<String> categories = dBCollection.distinct("categories",dbObject);

    return categories;
}

However when I test it using this code:

@Test
public void testListCategories(){
    List<String> categories = Product.listCategories("S");
    Assert.assertTrue(categories.size() > 0);
}

The test fails even though I know there are categories that start with S (have also tried a few others just to be sure).

Is it even possible to do this, if so do you have any pointers?

Thanks

2 Answers 2

1
BasicDBObject dbObject=new BasicDBObject();
dbObject.append(categories", input);

Now it will be like a where condition,

DBCollection dBCollection = ds.getCollection(Product.class);
 List<String> categories = dBCollection.distinct("categories",dbObject);
Sign up to request clarification or add additional context in comments.

Comments

1

The test fails even though I know there are categories that start with S (have also tried a few others just to be sure).

You need to perform a regex match using the $regex operator on the categories field to find distinct categories that start with a particular input.

Your updated code should look like:

BasicDBObject like = new BasicDBObject("$regex",
                         java.util.regex.Pattern.compile("^"+input,
                                                      Pattern.CASE_INSENSITIVE));
BasicDBObject query = new BasicDBObject("categories", like);
List<String> categories = dBCollection.distinct("categories",query);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.