MongoDB shell聚合在Morphia中不起作用

时间:2015-09-22 11:53:12

标签: mongodb shell morphia

考虑以下MongoDB集合:

{
"_id" : ObjectId("..."),
"myId": 12345,
"root": {
    basicData: {
        code: "CODE"
    }
    data: [
        {
            descriptions: {
                description: [
                    {
                        text: "...",
                        language: "de"
                    }
                ]
            }
        }
    ]
}}

我试图通过" myId"和"代码",但只有一种特定语言的描述。在shell中,以下命令似乎正常工作:

db.Items.aggregate([
  { "$match" : { "myId" : 40943 , "root.basicData.code" : "A_CODE"}}, 
  { "$unwind" : "$root.data"}, 
  { "$unwind" : "$root.data.descriptions.description"}, 
  { "$match" : { "root.data.descriptions.description.language" : "de"}}
])

在Morphia中,我尝试执行以下操作以获得相同的结果:

AggregationPipeline pipeline = dataStore.createAggregation(Item.class);

Query<Item> matchIdAndCode = dataStore.createQuery(Item.class);
matchIdAndCode.field("myId").equal(myid);
matchIdAndCode.field("root.basicData.code").equal(code);
pipeline.match(matchIdAndCode);

pipeline.unwind("root.data");
pipeline.unwind("root.data.descriptions.description");

Query<Item> matchLanguage = dataStore.createQuery(Item.class);
matchLanguage.field("root.data.descriptions.description.language").equal(language);
pipeline.match(matchLanguage);

Iterator<Item> itemAggregate = pipeline.aggregate(Item.class);

但迭代器不包含任何项目。我不知道在哪里搜索更多错误,特别是因为当我将morphia聚合管道中的阶段复制到shell时,我得到了预期的结果。

2 个答案:

答案 0 :(得分:0)

你错过了以下行中的$符号

pipeline.unwind( “root.data”);

pipeline.unwind( “root.data.descriptions.description”);

应该是

pipeline.unwind( “$ root.data”);

pipeline.unwind( “$ root.data.descriptions.description”);

答案 1 :(得分:0)

作为一种解决方法,我现在使用了MongoDB Java驱动程序。我的工作解决方案:

List<DBObject> stages = new ArrayList<DBObject>();
DBCollection collection = dataStore.getCollection(Item.class);

// match
DBObject matchFields = new BasicDBObject("myId", myid);
matchFields.put("code", code);
DBObject match = new BasicDBObject("$match", matchFields );
stages.add(match);

// unwind
DBObject unwindDescriptiveData = new BasicDBObject("$unwind", "$root.data");
stages.add(unwindDescriptiveData);
DBObject unwindDescription = new BasicDBObject("$unwind", "$root.data.descriptions.description");
stages.add(unwindDescription);

// match
DBObject languageMatchFields = new BasicDBObject("root.data.descriptions.description.language", language);
DBObject languageMatch = new BasicDBObject("$match", languageMatchFields );
stages.add(languageMatch);

AggregationOutput aggregate = collection.aggregate(stages);

可以再次使用Morphia完成对pojo的映射:

List<Item> items = new ArrayList<Item>();
for (Iterator<DBObject> iterator = aggregate.results().iterator(); iterator.hasNext();) {
  items.add(morphia.fromDBObject(Item.class, iterator.next()));
}