MongoDB elemMatch subdocuments

被刻印的时光 ゝ 提交于 2019-12-06 06:30:20

问题


I have the following data structure

{
    "_id" : ObjectId("523331359245b5a07b903ccc"),
    "a" : "a",
    "b" : [
        {
            "c" : {
                "_id" : ObjectId("5232b5090364678515db9a82"),
                "d" : "d1"
            }
        },
        {
            "c" : {
                "_id" : ObjectId("5232b5090364678515db9a83"),
                "d" : "d2"
            }
        }
    ]
}

For the following queries, mongo returns

> db.test.find({b : {$elemMatch : {'c.d': 'd1'}}}).count();
1
> db.test.find({b : {$elemMatch : {c: {d: 'd1'}}}}).count();
0

Unfortunately, for the following statements

B b = new B();
C c = new C();
b.c = c;
b.c.d = "d1";
createQuery().field("b").hasThisElement(b).asList();

Morphia generates db.test.find({b : {$elemMatch : {c: {d: 'd1'}}}}) which returns 0 match.

Is this a mongo bug or a morphia bug? Is there any workaround for me to get the matched document?

  • Please note that in the real world practice, I have 2 conditions for elemMatch, hence I have to use "elemMatch", not "dot notation" match. The above is just to simplify my case for easy viewing.
  • I'm running Mongodb 2.4.6 and Morphia 1.2.3

Thanks!


回答1:


It is too late, but maybe others can found it handy.

I found that solution https://groups.google.com/forum/#!topic/morphia/FlEjBoSqkhg

updateQuery.filter("b elem",
BasicDBObjectBuilder.start("c.d", "d1").get());


来源:https://stackoverflow.com/questions/18791045/mongodb-elemmatch-subdocuments

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