【问题标题】:Add projection to morphia query向morphia查询添加投影
【发布时间】:2013-03-20 21:47:06
【问题描述】:

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

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

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

谢谢

【问题讨论】:

标签: java mongodb morphia


【解决方案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();

(没测试过,应该是这样的)

【讨论】:

  • 使用 Morphia 1.1.0 对我不起作用。 List&lt;User&gt; list = ds.find(User.class).retrievedFields(false, "password").asList(); 这仍然返回所有带有password 字段的User 文档。
【解决方案2】:
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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多