首先要记一下根据 DBREF 的ObjectId 以及根据 ref 集合为条件查询问题.
在不同的可视化客户端里面显示的问题.
//某客户端显示这样,直接CMD查询也是这样显示.这样我无法看懂find条件 { "_id" : ObjectId("58ae865f7dde420cd0eae39f"), "className" : "com.thesys.morphia.dbref.DbrefTest$Book", "price" : "60.0", "author" : DBRef("Author", ObjectId("58ae865f7dde420cd0eae39e"))}
换了一个客户端
//同一个数据显示的格式,根据这样尝试查询 { "_id" : ObjectId("58ae865f7dde420cd0eae39f"), "className" : "com.thesys.morphia.dbref.DbrefTest$Book", "price" : "60.0", "author" : { "$ref" : "Author", "$id" : ObjectId("58ae865f7dde420cd0eae39e") }}
以下两个shell均可查询
db.Book.find({"author.$ref":"Author"})db.Book.find({ "author.$id":ObjectId("58ae865f7dde420cd0eae39e")})
以下是我的测试代码,使用morphia
@RunWith(JUnit4.class)public class DbrefTest { static final Morphia morphia = new Morphia(); static final Datastore datastore = morphia.createDatastore(new MongoClient(),"BookTest"); @Entity static class Book{ @Id private ObjectId id;//id private String name;//书名 private double price;//价格 @Reference private Author author; } @Entity static class Author{ @Id private ObjectId id;//id private String name;//作者名称 private String nationality;//国籍 } public static void main(String[] args) { Author author = new Author(); author.setName("大仲马"); author.setNationality("法国"); datastore.save(author); Book book = new Book(); book.setAuthor(author); datastore.save(book); } @Test public void testQuery(){ Queryquery = datastore.createQuery(Book.class); System.out.println(query.count()); List books = query.asList(); System.out.println(books.get(0).getAuthor().getName()); } @Test public void testUpdate(){ //注意根据ID查询不能传入String 必须是ObjectId Query query = datastore.createQuery(Book.class).field("_id").equal(new ObjectId("58ae7f837dde423968454e62"));// System.out.println(query.get().price);//直接获取结果集第一个// datastore.get(Book.class,new ObjectId("58ae7f837dde423968454e62")).price //直接根据ID查询一个文档 UpdateOperations updateOperation = datastore.createUpdateOperations(Book.class).set("name","三个火枪手").set("price", 55); datastore.updateFirst(query, updateOperation);//.更新第一个找到的 } //聚合管道,投射 @Test public void testAggregation(){ //把price 重命名为 name AggregationPipeline aggregationPipeline = datastore.createAggregation(Book.class).project(Projection.projection("name","price")); Iterator books = aggregationPipeline.aggregate(Book.class); System.out.println(books.next().getName());//打印出name : 60.0 }}