3

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

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

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

谢谢

4

2 回答 2

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();

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

于 2013-03-20T22:54:10.607 回答
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());
}
于 2015-11-05T10:49:14.770 回答