我的产品集合中有两个文档:
{ _id: '123', name:'tv abc', categories:['electronics','promo','cellbattery'] },
{ _id: '124', name:'phone xyz', categories:['electronics','sim','cellphones','promo'] }
我希望我的用户在搜索输入文本字段中键入“el”并获取此列表:
['electronics','cellbattery','cellphones']
我写了这个查询:
DBCollection collection = getDatastore().getCollection(Products.class);
DBObject query = new BasicDBObject( "categories", Pattern.compile(queryTerm) );
return collection.distinct( "categories", query );
其中 queryTerm 是“el”,第一行来自 Morphia,只是获取集合。
不幸的是,它返回整个类别列表、不同的值,而不仅仅是匹配正则表达式的值。
我做错了什么?
最佳答案
当数组元素满足 find/distinct 中指定的查询条件时,将返回整个文档,而不仅返回匹配的数组元素。为了实现你想要的,你需要使用 aggregation framework
。我在下面提供了可以在 shell 中执行的 Mongo 查询。这应该可以帮助您用 Java 重写它。
db.Products.aggregate([
// Match only those documents that have atleast one category satisfying regex `/el/`
{$match: {categories: /el/}},
// De-normalize the 'categories' array
{$unwind: "$categories"},
// Get only those array elements matching regex '/el/'
{$match: {categories: /el/}},
// Group by the array elements to get distinct value
{$group: {_id: "$categories"}}
])
关于java - Java+MongoDB 中数组字段的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606986/