我试图在这里做一个简单的MongoDB聚合。基本上我有这样的文件:
{
timestampInMs: 1444094140442,
records: [
{
value: "testvalue",
experiment: {
id: "56105b0af2763b25806d1365",
name: "integrationtest-kkkk",
created: "2015-10-03T22:47:38.479+0000",
updated: null
},
sensorId: "testsensor",
dataType: 1
},
{
value: "testvalue2",
experiment: {
id: "56105b0af2763b25806d1365",
name: "integrationtest-kkkk",
created: "2015-10-03T22:47:38.479+0000",
updated: null
},
sensorId: "testsensor2",
dataType: 1
},
{
value: "testvalue3",
experiment: {
id: "56105b0af2763b25806d1365",
name: "integrationtest-kkkk",
created: "2015-10-03T22:47:38.479+0000",
updated: null
},
sensorId: "testsensor3",
dataType: 1
},
{
value: "testvalue4",
experiment: {
id: "56105b0af2763b25806d1365",
name: "integrationtest-kkkk",
created: "2015-10-03T22:47:38.479+0000",
updated: null
},
sensorId: "testsensor4",
dataType: 1
}
],
created: "2015-10-06T01:15:40.501+0000",
updated: "2015-10-06T01:15:40.528+0000"
}
java模型看起来像这样
@Entity("sensordatadocs")
@Indexes ({
@Index(fields = @Field("timestampInMs"), options = @IndexOptions(name = "timestamp_ms_index"))
})
public class DbSensorDataDocument {
@Id
// Should be milliseconds since Epoch
private Long timestampInMs;
@Embedded
private List<DbSensorDataRecord> records;
private Date created;
private Date updated;
}
public class DbSensorDataRecord {
private String value;
@Reference
private Experiment experiment;
private String sensorId;
private int dataType;
}
当我使用数据库查询时
db.sensordatadocs.aggregate([{$unwind: "$records"}])
它给了我4份文件,每份文件&#34;记录&#34;包含与原始数组中的项对应的单个项。但是,当我使用Morphia的API时,就像这样:
Iterator<DbSensorDataDocument> iter = datastore.createAggregation(DbSensorDataDocument.class)
.unwind("records").aggregate(DbSensorDataDocument.class);
它将返回如下结果:
{
timestampInMs: 1444094140442,
sensorId: "testsensor",
value: "testvalue",
experimentId: "56105b0af2763b25806d1365",
dataType: 1
},
{
timestampInMs: 1444094140442,
sensorId: "testsensor",
value: "testvalue",
experimentId: "56105b0af2763b25806d1365",
dataType: 1
},
{
timestampInMs: 1444094140442,
sensorId: "testsensor",
value: "testvalue",
experimentId: "56105b0af2763b25806d1365",
dataType: 1
},
{
timestampInMs: 1444094140442,
sensorId: "testsensor",
value: "testvalue",
experimentId: "56105b0af2763b25806d1365",
dataType: 1
}
这就是我的迭代代码的样子:
while (iter.hasNext()) {
DbSensorDataDocument doc = iter.next();
final SensorDataRecord record = SensorDataUtils.flattenSensorDataDocument(doc);
result.add(record);
}
请注意,项目数是正确的,但&#34;记录&#34;中的值是正确的。不正确,实际上它们只是原始数组中**第一个项的值。为什么会这样?请帮忙。谢谢!
Morphia版本1.0.1
答案 0 :(得分:0)
该行为的原因是Morphia缓存问题。在您的情况下,Morphia将 DbSensorDataDocument 实体的所有结果视为同一行(因为相同的主键 timestampInMs ),并返回缓存版本。
要解决此问题,您必须从带有聚合投影的结果中排除字段 timestampInMs :
Iterator<DbSensorDataDocument> iter = datastore.createAggregation(DbSensorDataDocument.class)
.unwind("records").project(
Projection.projection("timestampInMs").suppress(),
Projection.projection("XXXXXX").aggregate(DbSensorDataDocument.class);
XXXXX是您要包含的字段。