参考ObjectID的Morphia查询

时间:2014-11-19 07:11:16

标签: mongodb reference morphia

这是我实体的定义:

@Entity("Comment")
public class Comment extends BaseEntity {

    @Reference
    private Merchant merchant;

    ...
}

@Entity("Merchant")
class Merchant extends BaseEntity{
    @Id
    @Property("id")
    protected ObjectId id;

    ...
}

这是我的数据:

comment:{
"_id": ObjectId("546c1ac64652e5180dc21577"),
"merchant" : DBRef("Merchant", ObjectId("546c1ac64652e5180dc21576")),

...
}

当我创建像:

这样的查询时
Query<Comment> query = ds.createQuery(Comment.class);
query.field("merchant").equal(new ObjectId("546c1ac64652e5180dc21576"));

commentDao.findOne(query);

没有返回结果,我想问一下用商家的ObjectId查询评论数据的正确方法是什么?

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

Query<Comment> query = ds.find(Comment.class).disableValidation()
    .field("Merchant").equal(new Key<>(Merchant.class, merchantId);

我认为你需要禁用验证,否则你会看到一些相当不必要的警告。

您可以直接查询DBRef ID,但由于DBRef本身是打字的,除非您有正当理由,否则我不会绕过它。

答案 1 :(得分:0)

我不喜欢Morphia使用DBRef的方式,因为它可以轻松地使用ObjectId(但DBRef确实包含允许您继承Merchant的类名)。

无论如何,你应该能够做到:

Query<Comment> query = ds.createQuery(Comment.class);
query.field("merchant.$id").equal(new ObjectId("546c1ac64652e5180dc21576")

或使用纯Java驱动程序

collection.find(new BasicDBObject("merchant",
    new BasicDBObject("$ref", "Merchant")
      .append("$id", new ObjectId("546c1ac64652e5180dc21576"))))

答案 2 :(得分:0)

正确的方法是使用ID获取Merchant对象,然后将其传递给Comment查询:

Query<Merchant> merchantQuery = ds.createQuery(Merchant.class);
merchantQuery.field("id").equal(new ObjectId(merchantId)); 
Merchant merchant = merchantQuery.get();     // Get the Merchant object

Query<Comment> commentQuery = ds.createQuery(Comment.class);
commentQuery.filter("merchant", merchant);
commentQuery.get()                           // Get the Comment object

答案 3 :(得分:0)

你可以使用mongodb驱动程序

var range_1 = document.getElementById('range_1');
var range_2 = document.getElementById('range_2');

range_1.addEventListener('change', function(){
  range_2.min = parseInt(range_1.value) + 1;
});

请注意json中的单个qoute。

OR

在Morphia中:

        MongoClient mongo =new MongoClient(mongoURI);
        DBCollection dbCollection =mongo.getDB("<your_db>").getCollection("Comment");
        DBObject dbObject = (DBObject) JSON.parse("{ 'merchant' : { '$ref' : 'Merchant' , '$id' : { '$oid' : '5693e72244ae9fe4803a4520'}}}");

        String json=JSON.serialize(dbCollection.find(dbObject));
相关问题