MongoDB elemMatch subdocuments

2019-04-12 10:54发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-04-12 11:38

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());
查看更多
登录 后发表回答