如何在为mongo形成查询时使用`.`

时间:2017-03-07 02:47:44

标签: mongodb morphia

如果之前已经提出这个问题,请道歉。

Query<Comment> q = createQuery();
        q.and(q.criteria("parent.$id").in(parentObjectIds), q.criteria("status")
                .equal(status.name()));

throws :  Can not use dot-notation past 'parent' could not be found in 'entity.Comment' while validating - parent.$id

虽然这很好。

db.getCollection('Comment').find({"parent.$id": {$in: [ObjectId("54c6b3e7e4b0df51ab756c51"),ObjectId("54dba376e4b026c6809c8f91") ]}})

我猜测Morphia生成的查询应该与此查询类似。

以下是评论文件:

{
"_id" : ObjectId("5511b0f2e4b0d7b61ff9764a"),
"entity" : {
    "$ref" : "Entity",
    "$id" : ObjectId("54c6b35fe4b0df51ab756c4f")
},
"content" : "Some Test Content",
"parent" : {
    "$ref" : "Comment",
    "$id" : ObjectId("54c6b3e7e4b0df51ab756c51")
},
"childCount" : 0,
"score" : 0

}

以下是查询中使用的引用注释类。

public class Comment extends Stats{

@Reference(lazy=true)
private EngEntity entity;   
private String content;
private Status status;
private boolean canReply;
@Reference
private Comment parent;
private int score;


public boolean isCanReply() {
    return canReply;
}

public Comment setCanReply(boolean canReply) {
    this.canReply = canReply;
    return this;
}

public Entity getEntity() {
    return entity;
}

public Comment setEntity(Entity entity) {
    this.entity = entity;
    return this;
}

public String getContent() {
    return content;
}

public Comment setContent(String content) {
    this.content = content;
    return this;
}

public Status getStatus() {
    return status;
}

public Comment setStatus(Status status) {
    this.status = status;
    return this;
}

public Comment getParent() {
    return parent;
}

public Comment setParent(Comment parent) {
    this.parent = parent;
    return this;
}


public int getScore() {
    return score;
}

public Comment setScore(int score) {
    this.score = score;
    return this;
}

}

1 个答案:

答案 0 :(得分:1)

DBRef可由name引用。

Query<Comment> q = datastore.createQuery(Comment.class);
Comment comment1 = new Comment();
comment1.setId(new ObjectId("54c6b3e7e4b0df51ab756d51"));
Comment comment2 = new Comment();
comment2.setId(new ObjectId("54dba376e4b026c6809c8f91"));
q.criteria("parent").in(Arrays.asList(comment1,comment2));
List<Comment> comments = q.asList();

没有验证:

DBRef可由$id引用。

Query<Comment> q = datastore.createQuery(Comment.class).disableValidation().field("parent.$id").hasAny‌​Of(parentObjectIds);
List<Comment> comments = q.asList();