向morphia查询添加投影

时间:2013-03-20 21:47:07

标签: java mongodb morphia

使用Morphia进行查询时,是否可以限制返回的字段(指定投影)?

在命令行上这样:
db.Institution.find({name:/ ^ Berlin /},{slug:1})

或者使用Java驱动程序: BasicDBObject projection = new BasicDBObject(“slug”,1); collection.find(new BasicDBObject(),projection);

由于

2 个答案:

答案 0 :(得分:1)

您这样做,请参阅https://code.google.com/p/morphia/wiki/Query#Ignoring_Fields

Pattern regex = Pattern.compile("^Berlin");
Query<InsitutionEntity> query = mongoDataStore.find(InsitutionEntity.class)
    .field("name").equal(regex)
    .retrievedFields(true, "slug").asList();

(没有测试它,但它应该像这样工作)

答案 1 :(得分:0)

BasicDBObject filter = new BasicDBObject();
filter.append("name", "whoever");

BasicDBObject projection = new BasicDBObject();
projection.append("fieldOne", 1); // 1 == True, it shows the Field.
projection.append("fieldTwo", 1);
projection.append("_id", 0) // 0 == False, it does not show the "_id"

List list = MorphiaObject.datastore.getCollection(MyClass.class).find(filter, projection).toArray();
for (Object each : list) {
    System.out.println("Each: " + each.toString());
}