MongoDb聚合$在集合列表中

时间:2016-10-13 18:02:16

标签: mongodb mongodb-query spring-data aggregation-framework

BasicDBObject matchDBObejct = new BasicDBObject('$match',
            new BasicDBObject("type", ArticleSourceType.MICROBLOGS.toString())
           .append(trackInsightGraphFilterCO.getMetricFeild(), new BasicDBObject('$exists', true).append('$ne', ""))
    )
BasicDBObject groupDBObject = new BasicDBObject('$group', new BasicDBObject("_id", '$' + trackInsightGraphFilterCO.getMetricFeild()).append("total", new BasicDBObject('$sum', 1)))
BasicDBObject limitDBObject = new BasicDBObject('$sort', new BasicDBObject("total", -1))
BasicDBObject sortDbObject = new BasicDBObject('$limit', 10);
List<BasicDBObject> pipeline = [matchDBObejct, groupDBObject, limitDBObject, sortDbObject];

我上面的查询运行正常 - 但是当我在匹配查询中添加其他参数时,我没有得到任何结果。

.append("track",new BasicDBObject('$in',tracks))

其中tracks是Track域的列表.toString(); 即 -

List<Track> trackDomainObjects;
for(Track track:trackDomainObjects){
tracks.add(track.toString())
}

我的匹配查询就像这样 -

BasicDBObject matchDBObejct = new BasicDBObject('$match',
            new BasicDBObject("type", ArticleSourceType.MICROBLOGS.toString())
                    .append("track",new BasicDBObject('$in',tracks))
                    .append(trackInsightGraphFilterCO.getMetricFeild(), new BasicDBObject('$exists', true).append('$ne', ""))
    )

控制台中没有异常,我的Mongo DB中有数据。 我的下面的控制台查询给了我数据 -

db.socialNotification.aggregate([ 
{$match:{"type":"MICROBLOGS","track":{$in:[DBRef('track',ObjectId("57f5fe0ce4b0e960f6d6ab9a")),DBRef('track',ObjectId("57f5fe2be4b0e960f6d6ac42"))]},"authorLocation" : { $exists : true, $ne : "" } }}, 
{ $group: { _id: "$authorLocation", total: { $sum: 1 } } }, 
{$sort:{ total:-1}},
{$limit: 10} ])

1 个答案:

答案 0 :(得分:0)

从你的问题我读到:

where tracks is list of Track domain .toString(); ie-

但是在你的工作示例中,我看到了:

{$match:{"type":"MICROBLOGS","track":{$in:[DBRef('track',ObjectId("57f5fe0ce4b0e960f6d6ab9a")),DBRef('track',ObjectId("57f5fe2be4b0e960f6d6ac42"))]},"authorLocation" : { $exists : true, $ne : "" } }}, 

在您的工作示例中,您有一个ObjectIds列表。 确保代码中的“跟踪”也是 ObjectIds列表!当您传递字符串列表时,它将无法正常工作