Morphia - using hasAllOf and hasThisElement together

坚强是说给别人听的谎言 提交于 2019-12-11 01:22:51

问题


I have a mongo collection named 'comment' which has documents which have a structure similar to this :

{
"_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 using a mongo query which would look like this :

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

The number of subdocuments I match inside the 'tags' will be variable. In the above query I am trying to match 2 sets of combinations.

Here is what I have tried so far:

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

            Query<CommentDo> t =
                    getMongoDAORead().getDatastore()
                    .createQuery(CommentDoImpl.class)
                    .field("tags").hasThisElement(tag).disableValidation();

This would form the following mongo query :

{"ctags":{"$elemMatch":{"name":"women","type":3}}}

Now to have more than one combination, I try to create a list of TagsDo:

List<TagsDo> tag = new ArrayList<TagsDo>();
TagsDo tag1 = new TagsDo("women", null, 3);
TagsDo tag2 = new TagsDo("clothing", null, 1);

Query<CommentDo> t =
                getMongoDAORead().getDatastore()
                .createQuery(CommentDoImpl.class)
                .field("tags").hasThisElement(Arrays.asList(tag.toArray)).disableValidation();

This forms the following mongo query :

{ "ctags" : 
     { "$elemMatch" : [ { "className" : "com.dal.comments.TagsDo" , "name" : "handbags" , "type" : 3} , 
                        { "className" : "com.dal.comments.TagsDo" , "name" : "web" , "type" : 0}]}}

I have one problem above,

-> The 'elemMatch' should appear twice and not just once.


After that is done, I need to use 'hasAllOf' which will add the '$alll' keyword to the query.

来源:https://stackoverflow.com/questions/21691198/morphia-using-hasallof-and-hasthiselement-together

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