mongodb java groupby查询转换

时间:2014-10-15 17:32:29

标签: java mongodb

一个mongodb新手。我一直在使用Mongo java驱动程序,到目前为止一切顺利。

我已成功使用DBCollection.aggregate - 我正在传递:

$match
$project
$group
$sort

例如,我一直在设置标准:

Map<String, Object> match_criteria;
match_criteria.put(“properties.type”, “monuments”);

DBObject match = new BasicDBObject();
match.putAll(match_criteria); //was just setting from Map
DBObject match_dbobj = new BasicDBObject("$match", match);
.
.
.
.
.in the same way was populating $project, $group and $sort

然后正在调用

DBCollection.aggregate(match_dbobj, project_dbobj, group_dbobj, sort_dbobj)

但现在使用这种方法转换以下mongo shell查询时遇到问题:

db.test.aggregate({
    $match:{             ---> still can pass with Map
        "properties.type":'monuments',
    }
},
{
    $project:{           ---> still can pass with Map
        "props.country":1,
        "attrs.time":1,
        "attrs.status":1
    }
},
{
    $group:{              ---> trying to find a way to handle $group from java code
        _id:{           
            status:'$attrs.status',
            country:'$props.country'
        },
        time:{
            $last:'$attrs.time'
        }
    }
}
)

如何转换$group - 我无法再使用Map构建。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在您的示例中,$group是一个嵌套的DBObject,因此创建它的方式是:

// Create the group sub documents
DBObject idDocument=new BasicDBObject("status","$attrs.status").append("country","$props.country");
DBObject timeDocument=new BasicDBObject("$last","$attrs.time");

// Create the group document
DBObject groupDocument=new BasicDBObject("_id",idDocument).append("time",timeDocument);

// Create the whole group statement
DBObject group=new BasicDBObject("$group", groupDocument);