Morphia - Query based on a subdocument

社会主义新天地 提交于 2020-01-06 08:36:11

问题


I have a mongo collection which has documents which look like below :

{
"_id" : ObjectId("9873214jkhdkfjdsf8324"),
"nm" : "test",
"sts" : 1,
"updby" : NumberLong(0),
"tags" : [ 
    {
        "name" : "women", 
        "rank" : 1, 
        "type" : 3 
    }, 
    {
        "name" : "men",
        "rank" : 1
    }, 
    {
        "name" : "clothing",
        "rank" : 2,
        "type" : 1
    }
]

}

I want to query the collection such that I want all the documents which have "name": "women" and "type" : 3 inside the tags subdocument of each document which is returned.

I know that the mongo query should be something like this :

db.collection.find("tags":{
            $all:[
                {"$elemMatch":{"name":"women","type":3}},               
            ]})

I tried using the 'hasthiselement' provided by morphia, but I am not able to form the exact query which I want.

 getMongoDAORead().getDatastore().createQuery(test.class)
                .field("tags").hasThisElement("name").equal("women");

This query doesn't seem to be correct. Can someone help me form the correct query?


回答1:


I fixed this by doing the following:

I created a object of the Tags Class and initialized it:

Tags tag = new Tags("women", null, 3);

Query<MyClass> t = getMongoDAORead().getDatastore()
        .createQuery(MyClass.class)
        .field("ctags").hasThisElement(tag);


来源:https://stackoverflow.com/questions/21672758/morphia-query-based-on-a-subdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!